﻿using DevExpress.Charts.Model;
using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using DevExpress.Xpf.Charts;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Trade;
using Prism.Services.Dialogs;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BindableBase = Prism.Mvvm.BindableBase;
using PlaceOrder_Core.PlaceOrderModels.Base;
using System.Text.RegularExpressions;
using System.Windows;
using DevExpress.Mvvm.POCO;
using IDialogService = Prism.Services.Dialogs.IDialogService;
using System.Windows.Media;
using PlaceOrder_Core.Helper;
using System.Net.WebSockets;
using PlaceOrder_Shared.Models.Daily;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.Services.Instances;
using DailyData = PlaceOrder_Core.Services.Instances.DailyData;
using DevExpress.Pdf.Native.BouncyCastle.Asn1.X509;
using Newtonsoft.Json;
using System.IO;
using PlaceOrder_Client.Models.Common;
using PlaceOrder_Shared.Models.Common;
using HandyControl.Controls;
using System.Diagnostics;
using System.Windows.Controls;
using MessageBox = HandyControl.Controls.MessageBox;
using DevExpress.Internal.WinApi.Windows.UI.Notifications;
using HandyControl.Tools.Extension;
using Microsoft.VisualBasic.Logging;
using PlaceOrder_Client.Helper;
using System.Windows.Threading;
using DevExpress.XtraPrinting;
using PlaceOrder_Client.Views;
using DevExpress.Data.Browsing;
using log4net;
using Prism.DryIoc;
using System.Collections.Specialized;
using DevExpress.XtraRichEdit.Import.Doc;
using static PlaceOrder_Core.Services.Instances.DailyData;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json.Linq;
using DevExpress.Utils.About;
using DevExpress.XtraRichEdit.Model;
using System.ComponentModel;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Drawing.Drawing2D;
using DeliverySpeedConverter = PlaceOrder_Client.Helper.DeliverySpeedConverter;
using DevExpress.XtraRichEdit.Fields;
using PlaceOrder_Client.Models.Config;
using FastExpressionCompiler.LightExpression;
using DevExpress.XtraRichEdit.Layout;
using DevExpress.Xpf.Core;

namespace PlaceOrder_Client.ViewModels
{
    public class OrderViewModel : BindableBase, IDialogAware
    {
        //public string Title { get; set; } = "订单系统（客户端）";
        private int themeIndex;//主题标志（Dark、Light）

        public int ThemeIndex
        {
            get { return themeIndex; }
            set { themeIndex = value;RaisePropertyChanged();this.OnThemeIndexChanged(); }
        }

        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; RaisePropertyChanged(); }
        }


        private bool bIsConnected = false; //是否连接到服务端

        private bool bResponseReceived = false; //是否收到服务端反馈
        private bool bWaitingforResponse = false;//等服务端反馈？
        private BidsForTrade TotalBids = new BidsForTrade();

        private Guid CurrentGuid;//唯一Guid

        private bool blocking = false;  //只能一个个做
        #region 依赖属性
        private decimal minTradePrice;

        public decimal MinTradePrice
        {
            get { return minTradePrice; }
            set { minTradePrice = value;RaisePropertyChanged(); }
        }
        private decimal maxTradePrice;

        public decimal MaxTradePrice
        {
            get { return maxTradePrice; }
            set { maxTradePrice = value; RaisePropertyChanged(); }
        }

        private string msgToken = Guid.NewGuid().ToString();

        public string MsgToken
        {
            get { return msgToken; }
            set { msgToken = value; }
        }

        /// <summary>
        /// 是否收藏
        /// </summary>
        private bool isFavourite;

        public bool IsFavourite
        {
            get { return isFavourite; }
            set { isFavourite = value; RaisePropertyChanged(); }
        }


        /// <summary>
        ///选中买的 摆单
        /// </summary>
        private BidHistory _selectedBid;
        public BidHistory SelectedBid
        {
            get { return _selectedBid; }
            set
            {
                if (value != null && _selectedBid != value)
                {
                    _selectedBid = value; // 直接赋值
                    if (OrderListViewModel.IsQiangPing)
                    {
                        _selectedBid = null;
                    }
                    RaisePropertyChanged(nameof(SelectedBid)); // Notify property change

                }
            }
        }

        /// <summary>
        ///选中卖的 摆单
        /// </summary>
        private BidHistory _selectedOfr;
        public BidHistory SelectedOfr
        {
            get { return _selectedOfr; }
            set
            {
                if (value != null && _selectedOfr != value)
                {
                    _selectedOfr = value; // 直接赋值
                    if (OrderListViewModel.IsQiangPing)
                    {
                        _selectedOfr = null;
                    }
                    RaisePropertyChanged(nameof(SelectedOfr)); // Notify property change

                }
            }
        }


        /// <summary>
        /// 最大交易量
        /// </summary>
        private int maxVolumeAccount;

        public int MaxVolumeAccount
        {
            get { return maxVolumeAccount; }
            set { maxVolumeAccount = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 最大可买
        /// </summary>
        private int maxBidVolume;

        public int MaxBidVolume
        {
            get { return maxBidVolume; }
            set { maxBidVolume = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 最大可卖
        /// </summary>
        private int maxOfrVolume;

        public int MaxOfrVolume
        {
            get { return maxOfrVolume; }
            set { maxOfrVolume = value; RaisePropertyChanged(); }
        }

        private bool selectedOptionJia0 = true;

        /// <summary>
        /// +0 （默认加0）
        /// </summary>
        public bool SelectedOptionJia0
        {
            get { return selectedOptionJia0; }
            set { selectedOptionJia0 = value; RaisePropertyChanged(); }
        }

        private bool selectedOptionJia1 = false;

        /// <summary>
        /// +1 
        /// </summary>
        public bool SelectedOptionJia1
        {
            get { return selectedOptionJia1; }
            set { selectedOptionJia1 = value; RaisePropertyChanged(); }
        }


        private int bidCount;

        /// <summary>
        /// TKN笔数
        /// </summary>
        public int BidCount
        {
            get { return bidCount; }
            set { bidCount = value; RaisePropertyChanged(); }
        }


        private int ofrCount;

        /// <summary>
        /// GVN笔数
        /// </summary>
        public int OfrCount
        {
            get { return ofrCount; }
            set { ofrCount = value; RaisePropertyChanged(); }
        }

        private int trdCount;

        /// <summary>
        /// TRD笔数
        /// </summary>
        public int TrdCount
        {
            get { return trdCount; }
            set { trdCount = value; RaisePropertyChanged(); }
        }

        private int allCount;

        /// <summary>
        /// 总笔数
        /// </summary>
        public int AllCount
        {
            get { return allCount; }
            set { allCount = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 加载显示的东西
        /// </summary>
        private string loadingMessage = "加载中...";

        public string LoadingMessage
        {
            get { return loadingMessage; }
            set { loadingMessage = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 是否远期
        /// </summary>
        private bool isForward = false;

        public bool IsForward
        {
            get { return isForward; }
            set { isForward = value; RaisePropertyChanged(); RefreshDataByForward(); }
        }




        /// <summary>
        /// 交易数据
        /// </summary>
        private ObservableCollection<TradeHistoryRow> _trades;
        public ObservableCollection<TradeHistoryRow> Trades
        {
            get { return _trades; }
            set
            {
                if (_trades != null)
                {
                    _trades.CollectionChanged -= Trades_CollectionChanged;
                }

                _trades = value;
                RaisePropertyChanged();

                if (_trades != null)
                {
                    _trades.CollectionChanged += Trades_CollectionChanged;
                }
                UpdateFilterTrades();
            }
        }

        private void Trades_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            UpdateFilterTrades();
        }

        private ObservableCollection<TradeHistoryRow> _filteredTrades;
        public ObservableCollection<TradeHistoryRow> FilteredTrades
        {
            get { return _filteredTrades; }
            set
            {
                _filteredTrades = value;
                RaisePropertyChanged();
            }
        }



        /// <summary>
        /// 买入价格（绿色）
        /// </summary>
        private ObservableCollection<BidHistory> _bids;
        public ObservableCollection<BidHistory> Bids
        {
            get { return _bids; }
            set
            {
                if (_bids != null)
                {
                    //OnBidsCollectionChanged();
                }

                _bids = value;

                //if (_bids != null)
                //{
                //    _bids.CollectionChanged += OnBidsCollectionChanged;
                //}

                RaisePropertyChanged();
            }
        }

        private void OnBidsCollectionChanged()
        {
            // Your custom logic here.
            // For example, preserving the selected item:
            var selectedBid = SelectedBid;
            // Update the collection
            // Bids = new ObservableCollection<BidHistory>(GetNewBids());

            // Restore the selected item if necessary
            if (selectedBid != null)
            {
                SelectedBid = Bids.FirstOrDefault(bid => bid.BrokerName == selectedBid.BrokerName); // Assume BidHistory has a unique Id property
            }
        }

        /// <summary>
        /// 卖出价格（红色）
        /// </summary>
        private ObservableCollection<BidHistory> _ofrs;
        public ObservableCollection<BidHistory> Ofrs
        {
            get { return _ofrs; }
            set
            {
                _ofrs = value;
                RaisePropertyChanged();
            }
        }

        private bool _isBuyChecked = true;

        public bool IsBuyChecked
        {
            get { return _isBuyChecked; }
            set
            {
                if (_isBuyChecked != value)
                {
                    _isBuyChecked = value;
                    RaisePropertyChanged();
                }
            }
        }

        private bool _isSellChecked;

        public bool IsSellChecked
        {
            get { return _isSellChecked; }
            set
            {
                if (_isSellChecked != value)
                {
                    _isSellChecked = value;
                    RaisePropertyChanged();
                }
            }
        }

        /// <summary>
        /// 显示交易状态
        /// </summary>
        private string status;

        public string Status
        {
            get { return status; }
            set { status = value; RaisePropertyChanged(); }
        }


        private static List<string> StaticTsCodes = null; //债券代码

        private List<string> _tsCodes;
        public List<string> TsCodes
        {
            get { return _tsCodes; }
            set
            {
                if (_tsCodes != value)
                {
                    _tsCodes = value;
                    RaisePropertyChanged();
                }
            }
        }

        /// <summary>
        /// 交易量
        /// </summary>
        private decimal volumeValue;

        public decimal VolumeValue
        {
            get { return volumeValue; }
            set
            {
                if (volumeValue != value)
                {
                    volumeValue = value;
                    RaisePropertyChanged();
                }
            }
        }


        /// <summary>
        /// 下单价格
        /// </summary>
        private decimal orderPrice;

        public decimal OrderPrice
        {
            get { return orderPrice; }
            set { orderPrice = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 券号
        /// </summary>
        private string bondNumber;

        public string BondNumber
        {
            get { return bondNumber; }
            set { bondNumber = value; RaisePropertyChanged(); _=UpdateTitle(); }
        }

        private async Task UpdateTitle()
        {
           await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            {
                this.Title = $"{this.BondNumber}-{UserHelper.NickName}";
            });
        }

        /// <summary>
        /// 交易限额
        /// </summary>
        private string tradeLimit;

        public string TradeLimit
        {
            get { return tradeLimit; }
            set { tradeLimit = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 切换查看的日期区间
        /// </summary>
        private string cbDays;

        public string CbDays
        {
            get { return cbDays; }
            set { cbDays = value; RaisePropertyChanged(); }
        }

        private string legendStatus = "交易走势（当日）";

        public string LegendStatus
        {
            get { return legendStatus; }
            set { legendStatus = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 交割日
        /// </summary>
        private DateTime deliveryDate;

        public DateTime DeliveryDate
        {
            get { return deliveryDate; }
            set { deliveryDate = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 最近交割日，10.30后不能选今天
        /// </summary>
        private DateTime minDeliveryDate = DateTime.Now;

        public DateTime MinDeliveryDate
        {
            get { return minDeliveryDate; }
            set { minDeliveryDate = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 最远交割日，下一个非银交易日
        /// </summary>
        private DateTime maxDeliveryDate;

        public DateTime MaxDeliveryDate
        {
            get { return maxDeliveryDate; }
            set { maxDeliveryDate = value; RaisePropertyChanged(); }
        }




        /// <summary>
        /// 接收人
        /// </summary>
        private string target;

        public string Target
        {
            get { return target; }
            set { target = value; RaisePropertyChanged(); }
        }

        private ChatReceiver selectedReceiver;

        public ChatReceiver SelectedReceiver
        {
            get { return selectedReceiver; }
            set
            {
                selectedReceiver = value; RaisePropertyChanged(); if (selectedReceiver != null)
                {
                    this.Target = selectedReceiver?.Target;
                }
            }
        }


        private ObservableCollection<ChatReceiver> chatReceivers;
        public ObservableCollection<ChatReceiver> ChatReceivers
        {
            get { return chatReceivers; }
            set
            {
                if (chatReceivers != value)
                {
                    chatReceivers = value;
                    RaisePropertyChanged();
                }
            }
        }

        /// <summary>
        /// 加载中
        /// </summary>
        private bool isLoading;

        public bool IsLoading
        {
            get { return isLoading; }
            set { isLoading = value; RaisePropertyChanged(); }
        }


        public DelegateCommand<string> TSSelectionChangedCommand { get; private set; }
        public DelegateCommand VolumeValueChangedCommand { get; private set; }
        public DelegateCommand OrderPriceChangedChangedCommand { get; private set; }
        public DelegateCommand<string> BuyAndSellCheckedCommand { get; private set; }
        public DelegateCommand CbDaysChangedCommand { get; private set; }
        public DelegateCommand<string> ShortCutCommand { get; private set; }
        public DelegateCommand<string> ChangePriceCommand { get; private set; } //改价命令
        public DelegateCommand GetLatestPriceCommand { get; private set; } //获取最新价
        public DelegateCommand TestCommand { get; set; }
        public DelegateCommand TestCommand2 { get; set; }
        public DelegateCommand TestCommand3 { get; set; }
        public DelegateCommand TestCommand4{ get; set; }
        public DelegateCommand SendSocketCommand { get; private set; } //测试发送socket
        public DelegateCommand OpenViewCommand { get; private set; } //打开默认交易量画面
        public DelegateCommand SetTopMostCommand { get; private set; } //置顶页面

        public DelegateCommand ToggleFavouriteCommand { get; private set; } //收藏当前下单界面


        public DelegateCommand<BidHistory> SelectedBidCommand { get; private set; }
        public DelegateCommand<TradeHistoryRow> SelectedTradeCommand { get; private set; }

        #endregion

        private readonly IDailyData _dailyData;

        private readonly List<DateOnly> Holidays;
        private DailyOrderStatusViewModel _dailyOrderStatusViewModel;
        private LoadingAnimationViewModel _loadingAnimationViewModel;
        private TradeSimUser TradeUser = new TradeSimUser();
        public OrderViewModel(IDailyData dailyData, LoadingAnimationViewModel loadingAnimationViewModel)
        {
            GuidStr = Guid.NewGuid().ToString();
            _dailyData = dailyData;
            //_dailyOrderStatusViewModel = dailyOrderStatusViewModel;
            _loadingAnimationViewModel = loadingAnimationViewModel;

            TsCodes = OrderListViewModel.WhiteTscodeList;
            Task.Run(() =>
            {
                RenderFromConfig();
            });
            var chatReceiversResult =
             OrderListViewModel.ChatReceivers;
            ChatReceivers = chatReceiversResult.ToObservableCollection();
            ChatReceivers.Insert(0, new ChatReceiver()
            {
                Brokerid = -1,
                Target = "自动",
                Company = "自动",
                Id = 0
            });
            InitValueAsync();

            Messenger.Default.Register<List<LilyOccupyBrokerInfo>>(this, MessageToken.OccupyBrokerInfo, HandleOccupyBrokerInfoMessage);
            InitCommand();
            Holidays = OrderListViewModel.Holidays;



            Thread backThread = new Thread(StartConnection);
            backThread.Start();


            DoBackgroundWork();
            //Task.Run(() =>{
            //    DoBackgroundWork();
            //});


            PropertyChanged += OrderViewModel_PropertyChanged; ;

            // 启动异步任务
            Task.Run(() => UpdateVolumeAsync());

            // 注册消息接收方法
            //DailyOrderStatusViewModel viewModel = DailyOrderStatusDataContext as DailyOrderStatusViewModel;
        }

        private async Task UpdateVolumeAsync()
        {
            // 等待 2 秒
            await Task.Delay(3500);

            UserTradeVolumeConfig volume = OrderListViewModel.VolumeConfigs.FirstOrDefault(x => x.Tscode == this.BondNumber);

            if (volume != null)
            {
                VolumeValue = volume.Volume;
            }
            else
            {
                VolumeValue = 2000;
                //volume = new UserTradeVolumeConfig() { Tscode = TsInfo.tsCode, Volume = 2000, UserId = UserHelper.UserID };
                //_dailyData.AddUserTradeVolumeConfig(volume);
                //OrderListViewModel.VolumeConfigs.Add(volume);
            }
        }

        // 创建一个简单的类来存储 BrokerId 和 occupy 的信息
        public class BrokerInfo
        {
            public int BrokerId { get; set; }
            public bool Occupy { get; set; }
            public int? UserId { get; set; }

            public override string ToString()
            {
                return $"中介ID: {BrokerId}, 是否占用：{(Occupy ? "是" : "否")},用户ID{UserId}";
            }
        }

        public List<BrokerInfo> OccupiedBroker { get; set; }

        private readonly object _brokerLock = new object();


        public List<BrokerInfo> BrokerInfosByLily = new List<BrokerInfo>();
        /// <summary>
        /// 这里 Disabled--- 有点歧义，[false 代表 禁用，true代表 正常] 舍弃，false 代表正常，true代表被禁用
        /// </summary>
        /// <param name="list"></param>
        /// 
        private void HandleOccupyBrokerInfoMessage(List<LilyOccupyBrokerInfo> list)
        {
            lock (_brokerLock)
            {
                try
                {
                    // 获取所有需要禁用的 brokerid
                    BrokerInfosByLily = list.Select(o => new BrokerInfo
                    {
                        BrokerId = o.BrokerId,
                        Occupy = o.Occupy,
                        UserId = o.Occupyier
                    }).ToList();

                    //foreach (var item in BrokerInfosByLily)
                    //{
                    //    AppLog.WriteError("lily数据：" + item?.ToString());
                    //}

                    // 查找所有 occupy=true 且 UserId 等于当前用户的 brokers
                    var occupiedBrokers = BrokerInfosByLily.Where(b => b.Occupy && b.UserId == UserHelper.UserID).ToList();

                    if (occupiedBrokers.Any())
                    {
                        OccupiedBroker = occupiedBrokers;

                        // 只有自己能下单的情况
                        foreach (var receiver in ChatReceivers)
                        {
                            var info = BrokerInfosByLily.FirstOrDefault(b => b.BrokerId == receiver.Brokerid);
                            if (info != null)
                            {
                                if (occupiedBrokers.Any(b => b.BrokerId == info.BrokerId))
                                {
                                    PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                                    {
                                        this.SelectedReceiver = ChatReceivers.Where(o => o.Brokerid == info.BrokerId).FirstOrDefault();
                                        //this.Bids.Where(o => o.BrokerId == info.BrokerId).FirstOrDefault().IsBrokerSelected = true;
                                        //this.Ofrs.Where(o => o.BrokerId == info.BrokerId).FirstOrDefault().IsBrokerSelected = true;
                                    });

                                    receiver.IsDisabled = false; // 高亮显示
                                }
                                else
                                {
                                    receiver.IsDisabled = true; // 变灰
                                }
                            }
                            else
                            {
                                receiver.IsDisabled = true; //true=被占用
                            }
                        }
                    }
                    else
                    {
                        OccupiedBroker = new List<BrokerInfo>();
                        //// 自己没下单的情况，把别人占用的中介变灰，其他中介高亮显示
                        //PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                        //{
                        //    // 将 Bids 集合中每个项的 IsBrokerSelected 属性设置为 false
                        //    this.Bids.ForEach(bid => bid.IsBrokerSelected = false);

                        //    // 将 Ofrs 集合中每个项的 IsBrokerSelected 属性设置为 false
                        //    this.Ofrs.ForEach(ofr => ofr.IsBrokerSelected = false);
                        //});
                        foreach (var receiver in ChatReceivers)
                        {
                            var info = BrokerInfosByLily.FirstOrDefault(b => b.BrokerId == receiver.Brokerid);
                            if (info != null)
                            {
                                if (info.Occupy)
                                {
                                    if (SelectedReceiver != null)
                                    {
                                        if (SelectedReceiver.Brokerid == receiver.Brokerid)
                                        {
                                            SelectedReceiver = ChatReceivers.FirstOrDefault();
                                        }
                                    }

                                    receiver.IsDisabled = true; // 被别人占用，变灰
                                }
                                else
                                {
                                    receiver.IsDisabled = false; // 未被占用，高亮显示
                                }
                            }
                            else
                            {
                                receiver.IsDisabled = false; // 未占用
                            }
                        }
                    }

                    var chatReceiver = ChatReceivers.FirstOrDefault(o => o.Brokerid == -1);

                    if (chatReceiver != null)
                    {
                        // If an item is found, set IsDisabled to false
                        chatReceiver.IsDisabled = false;
                    }

                    //foreach (var receiver in ChatReceivers)
                    //{
                    //    if (receiver.IsDisabled == false)
                    //    {
                    //        AppLog.WriteError($"{receiver.ChatId}---Disabled = false");
                    //    }
                    //    else
                    //    {
                    //        AppLog.WriteError($"{receiver.ChatId}---Disabled = true");
                    //    }
                    //}

                    PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                    {
                        if (this.Ofrs != null)
                        {
                            UpdateIsBrokerOccupied(this.Ofrs);
                        }
                        if (this.Bids != null)
                        {
                            UpdateIsBrokerOccupied(this.Bids);
                        }
                    });

                    // ChatReceivers = new ObservableCollection<ChatReceiver>(ChatReceivers);
                }
                catch (Exception ex)
                {
                    AppLog.WriteError("HandleOccupyBrokerInfoMessage 处理" + ex.Message + ex.StackTrace);
                }
            }
        }

        //private void HandleOccupyBrokerInfoMessage(List<LilyOccupyBrokerInfo> list)
        //{
        //    lock(_brokerLock)
        //     {
        //        try
        //        {
        //            // 获取所有需要禁用的 brokerid
        //             BrokerInfosByLily = list.Select(o => new BrokerInfo
        //            {
        //                BrokerId = o.BrokerId,
        //                Occupy = o.Occupy,
        //                UserId = o.Occupyier
        //            }).ToList();

        //            foreach(var item in BrokerInfosByLily)
        //            {
        //                AppLog.WriteError("lily数据："+item?.ToString());
        //            }

        //            // 查找第一条 occupy=true 且 UserId 等于当前用户的 broker
        //            var userOccupiedBroker = BrokerInfosByLily.FirstOrDefault(b => b.Occupy && b.UserId == UserHelper.UserID);
        //            // 查找所有 occupy=true 且 UserId 等于当前用户的 brokers
        //            var occupiedBrokers = BrokerInfosByLily.Where(b => b.Occupy && b.UserId == UserHelper.UserID).ToList();
        //            if (userOccupiedBroker != null)
        //            {
        //                OccupiedBroker = userOccupiedBroker;
        //                // 只有自己能下单的情况
        //                foreach (var receiver in ChatReceivers)
        //                {
        //                    var info = BrokerInfosByLily.FirstOrDefault(b => b.BrokerId == receiver.Brokerid);
        //                    if (info != null)
        //                    {

        //                        if (info.BrokerId == userOccupiedBroker.BrokerId)
        //                        {
        //                            PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //                            {
        //                                this.SelectedReceiver = ChatReceivers.Where(o => o.Brokerid == info.BrokerId).FirstOrDefault();
        //                                //this.Bids.Where(o => o.BrokerId == info.BrokerId).FirstOrDefault().IsBrokerSelected = true;
        //                                //this.Ofrs.Where(o => o.BrokerId == info.BrokerId).FirstOrDefault().IsBrokerSelected = true;
        //                            });

        //                            receiver.IsDisabled = false; // 高亮显示
        //                        }
        //                        else
        //                        {
        //                            receiver.IsDisabled = true; // 变灰
        //                        }
        //                    }
        //                    else
        //                    {
        //                        receiver.IsDisabled = true; //true=被占用
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                OccupiedBroker = null;
        //                //// 自己没下单的情况，把别人占用的中介变灰，其他中介高亮显示
        //                //PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //                //{
        //                //    // 将 Bids 集合中每个项的 IsBrokerSelected 属性设置为 false
        //                //    this.Bids.ForEach(bid => bid.IsBrokerSelected = false);

        //                //    // 将 Ofrs 集合中每个项的 IsBrokerSelected 属性设置为 false
        //                //    this.Ofrs.ForEach(ofr => ofr.IsBrokerSelected = false);
        //                //});
        //                foreach (var receiver in ChatReceivers)
        //                {
        //                    var info = BrokerInfosByLily.FirstOrDefault(b => b.BrokerId == receiver.Brokerid);
        //                    if (info != null)
        //                    {
        //                        if (info.Occupy)
        //                        {
        //                            if(SelectedReceiver!=null)
        //                            {
        //                                if (SelectedReceiver.Brokerid == receiver.Brokerid)
        //                                {
        //                                    SelectedReceiver = ChatReceivers[0];
        //                                }
        //                            }

        //                            receiver.IsDisabled = true; // 被别人占用，变灰
        //                        }
        //                        else
        //                        {
        //                            receiver.IsDisabled = false; // 未被占用，高亮显示
        //                        }
        //                    }
        //                    else
        //                    {
        //                        receiver.IsDisabled = false; // 未占用
        //                    }
        //                }

        //            }
        //            var chatReceiver = ChatReceivers.Where(o => o.Brokerid == -1).FirstOrDefault();

        //            if (chatReceiver != null)
        //            {
        //                // If an item is found, set IsDisabled to false
        //                chatReceiver.IsDisabled = false;
        //            }

        //            //foreach (var receiver in ChatReceivers)
        //            //{
        //            //    if (receiver.IsDisabled == false)
        //            //    {
        //            //        AppLog.WriteError($"{receiver.ChatId}---Disabled = false");
        //            //    }
        //            //    else
        //            //    {
        //            //        AppLog.WriteError($"{receiver.ChatId}---Disabled = true");
        //            //    }
        //            //}


        //            PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //            {
        //                if(this.Ofrs!=null)
        //                {
        //                    UpdateIsBrokerOccupied(this.Ofrs);
        //                }
        //                if (this.Bids != null)
        //                {
        //                    UpdateIsBrokerOccupied(this.Bids);
        //                }

        //            });
        //            //ChatReceivers = new ObservableCollection<ChatReceiver>(ChatReceivers);
        //        }
        //        catch (Exception ex)
        //        {
        //            AppLog.WriteError("HandleOccupyBrokerInfoMessage 处理" + ex.Message + ex.StackTrace);
        //        }

        //    }



        //}

        private void OrderViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            //if (e.PropertyName == nameof(SelectedBid)|| e.PropertyName == nameof(SelectedOfr))
            //{
            //    if (sender is OrderViewModel viewModel)
            //    {
            //        // 获取选中买单的值
            //        var selectedBidValue = viewModel.SelectedBid;

            //        // 获取选中卖单的值
            //        var selectedOfrValue = viewModel.SelectedOfr;

            //        // 处理逻辑，例如打印值或进行其他操作
            //       if(selectedBidValue != null)
            //        {
            //            this.IsBuyChecked = selectedBidValue.BidType == BidHistory.enumBidType.Bid ? true : false;
            //            this.IsSellChecked = selectedBidValue.BidType == BidHistory.enumBidType.Ofr ? true : false;
            //            this.OrderPrice = selectedBidValue.Price;
            //            // 示例：将字符串转换为 decimal
            //            string volumeString = selectedBidValue.TotalVolume.ToString(); // 假设 Volume 是字符串类型
            //            if (decimal.TryParse(volumeString, out decimal volumeDecimal))
            //            {
            //                viewModel.VolumeValue = volumeDecimal;
            //                this.VolumeValue=volumeDecimal;
            //            }
            //            else
            //            {
            //                // 处理转换失败的情况，例如设置默认值或记录错误日志
            //                viewModel.VolumeValue = 0; // 默认值
            //                Console.WriteLine($"Failed to parse Volume: {volumeString}");
            //            }
            //        }
            //        if (selectedOfrValue != null)
            //        {
            //            this.IsBuyChecked = selectedOfrValue.BidType == BidHistory.enumBidType.Bid ? true : false;
            //            this.IsSellChecked = selectedOfrValue.BidType == BidHistory.enumBidType.Ofr ? true : false;
            //            this.OrderPrice = selectedOfrValue.Price;
            //            // 示例：将字符串转换为 decimal
            //            string volumeString = selectedOfrValue.TotalVolume.ToString(); // 假设 Volume 是字符串类型
            //            if (decimal.TryParse(volumeString, out decimal volumeDecimal))
            //            {
            //                viewModel.VolumeValue = volumeDecimal;
            //                this.VolumeValue = volumeDecimal;
            //            }
            //            else
            //            {
            //                // 处理转换失败的情况，例如设置默认值或记录错误日志
            //                viewModel.VolumeValue = 0; // 默认值
            //                Console.WriteLine($"Failed to parse Volume: {volumeString}");
            //            }
            //        }
            //        // 在这里添加你自己的逻辑
            //    }
            //}
        }

        private DispatcherTimer _timer;
        /// <summary>
        /// 根据权限来区分不同的后台任务
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void DoBackgroundWork()
        {
            //TradeUser = _dailyData.GetTradeSimSingleUser(UserHelper.UserID);
            //switch (TradeUser.UserStatus)
            //{

            //}

            // 初始化定时器
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(60); // 设置60秒间隔
            _timer.Tick += Timer_Tick;
            _timer.Start(); // 启动定时器
        }

        public int timerCount = 0;

        private int refreshCount = 0;

        private bool hasExecutedGetDeliveryDate = false; // 新增布尔变量
        /// <summary>
        /// 30S强制刷新一下成交页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private async void Timer_Tick(object? sender, EventArgs e)
        {
            try 
            {
                if (string.IsNullOrEmpty(this.BondNumber))
                {
                    return;

                }
                refreshCount++;

                if (refreshCount % 2 == 0)
                {
                    OnTsSelectionChangedAsync(this.BondNumber, false);
                    AppLog.WriteInfo($"2分钟 GUID_{this.MsgToken},强制刷新券码{this.BondNumber}");
                }

                if (refreshCount == 6)
                {
                    //十分钟重新订阅一次。 // 测试 改为6分钟 
                    AppLog.WriteInfo("OrderViewModel重新订阅Lily");
                    websocket.SubscribeTradeData(this.BondNumber, this.GuidStr);
                    //UpdateFilterTrades();
                    refreshCount = 0;
                }
                // 获取当前日期和时间
                DateTime now = DateTime.Now;

                // 判断是否为当天并且时间超过 10:30 AM
                if (now.TimeOfDay > new TimeSpan(10, 30, 0) && !hasExecutedGetDeliveryDate)
                {
                    GetDeliveryDate();
                    hasExecutedGetDeliveryDate = true; // 设置为已执行
                }
            }
            catch(Exception ex)
            {
                AppLog.WriteError("OrderViewModel定时报错" + ex.Message + ex.StackTrace);
            }

            //PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            //{
            //    if (string.IsNullOrEmpty(this.BondNumber))
            //    {
            //        return;
            //        //OnTsSelectionChangedAsync(this.BondNumber, false);

            //        //UpdateFilterTrades();
            //        //AppLog.WriteInfo($"强制页面刷新第{++timerCount}次");
            //    }
            //    refreshCount++;
            
            //    if(refreshCount%2==0)
            //    {
            //        OnTsSelectionChangedAsync(this.BondNumber, false);
            //        AppLog.WriteInfo($"两分钟 GUID_{this.MsgToken},强制刷新券码{this.BondNumber}");
            //    }

            //    if (refreshCount==6)
            //    {
            //        //十分钟重新订阅一次。 // 测试 改为8分钟 
            //        AppLog.WriteInfo("OrderViewModel重新订阅Lily");
            //        websocket.SubscribeTradeData(this.BondNumber, this.GuidStr);
            //        //UpdateFilterTrades();
            //        refreshCount = 0;
            //    }
            //    // 获取当前日期和时间
            //    DateTime now = DateTime.Now;

            //    // 判断是否为当天并且时间超过 10:30 AM
            //    if (now.TimeOfDay > new TimeSpan(10, 30, 0))
            //    {
            //        GetDeliveryDate();
            //    }
            //});


        }

        private async Task RefreshDailyStatus() // 声明为异步方法
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
                client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                // 创建一个包含用户ID的匿名对象
                var data = new { userId = UserHelper.UserID };

                // 将对象序列化为 JSON 字符串
                string json = JsonConvert.SerializeObject(data);

                // 创建 StringContent 对象，设置其内容和 Content-Type
                HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
                HttpResponseMessage res = await client.PostAsync($"{DataHelper.BaseConfig.HttpUrl}/tradeamountlimit/userlatestriskinfo", content);

                string tmp;
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    tmp = await res.Content.ReadAsStringAsync();

                    // 解析 JSON 字符串
                    JObject jsonObj = JObject.Parse(tmp);

                    // 获取 value 字段的内容
                    JObject valueObj = (JObject)jsonObj["value"];

                    // 解析并访问 value 字段中的属性
                    int maxvolume = (int)valueObj["maxVolume"];
                    int currentBid = (int)valueObj["currentBid"];
                    int currentOffer = (int)valueObj["currentOffer"];
                    decimal minProfitAlltime = (decimal)valueObj["minProfitAlltime"];
                    decimal minProfitDaily = (decimal)valueObj["minProfitDaily"];
                    decimal minBackDaily = (decimal)valueObj["minBackDaily"];
                    decimal profitAlltime = (decimal)valueObj["profitAlltime"];
                    int solidProfit = (int)valueObj["solidProfit"];
                    int floatProfit = (int)valueObj["floatProfit"];
                    int back = (int)valueObj["back"];
                    int limitBid = (int)valueObj["limitBid"];
                    int limitOffer = (int)valueObj["limitOffer"];

                    // 使用 Dispatcher.InvokeAsync 刷新 UI
                    PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                    {
                        this._dailyOrderStatusViewModel.MaxVolume = maxvolume;
                        this._dailyOrderStatusViewModel.MinProfitAllTime = minProfitAlltime;
                        this._dailyOrderStatusViewModel.ProfitAllTime = profitAlltime;
                        this._dailyOrderStatusViewModel.SolidProfit = solidProfit;

                        this._dailyOrderStatusViewModel.CurrentBid = currentBid;
                        this._dailyOrderStatusViewModel.MinProfitDaily = minProfitDaily;
                        this._dailyOrderStatusViewModel.FloatProfit = floatProfit;

                        this._dailyOrderStatusViewModel.CurrentOffer = currentOffer;
                        this._dailyOrderStatusViewModel.MinBackDaily = minBackDaily;
                        this._dailyOrderStatusViewModel.Back = back;
                    });
                }
            }
        }


        public OrderConfigClass config;
        /// <summary>
        /// 从配置文件读完成渲染
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void RenderFromConfig()
        {
            //string config_tmp = GetJsonFile();
            //if (config_tmp != "")
            //{
            //    config = JsonConvert.DeserializeObject<OrderConfigClass>(config_tmp);
            //    if (config.Volume < 2000)
            //    {
            //        VolumeValue = (decimal)config.Volume;
            //    }
            //    else
            //    {
            //        VolumeValue = 2000;
            //    }
            //}
        }
        private string GetJsonFile()
        {
            string json = string.Empty;
            using (FileStream fs = new FileStream("OrderConfig.json", FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                {
                    json = sr.ReadToEnd().ToString();
                }
            }
            return json;
        }


        private void InitCommand()
        {
            TSSelectionChangedCommand = new DelegateCommand<string>(async (tsCode) => await OnTsSelectionChangedAsync(tsCode));
            VolumeValueChangedCommand = new DelegateCommand(OnVolumeValueChanged);
            OrderPriceChangedChangedCommand = new DelegateCommand(OnOrderPriceChanged);
            BuyAndSellCheckedCommand = new DelegateCommand<string>(OnBuyAndSellCheckedChanged);
            CbDaysChangedCommand = new DelegateCommand(OnCbDaysChanged);
            ShortCutCommand = new DelegateCommand<string>(OnShortCutTriggered);
            //ChangePriceCommand = new DelegateCommand<string>(ChangePrice);
            GetLatestPriceCommand = new DelegateCommand(GetLatestPrice);
            SendSocketCommand = new DelegateCommand(() =>
            {
                websocket.client.SendAsync("111222");
            });
            OpenViewCommand = new DelegateCommand(OpenDefaultTradingVolumeView);
            SetTopMostCommand = new DelegateCommand(SetTopMostWindow);

            SelectedBidCommand = new DelegateCommand<BidHistory>(SelectedBidHandle);
            SelectedTradeCommand = new DelegateCommand<TradeHistoryRow>(SelectedTradeHandle);

            ToggleFavouriteCommand = new DelegateCommand(ToggleFavouriteHandle);

            TestCommand = new DelegateCommand(Test);
            TestCommand2 = new DelegateCommand(Test2);
            TestCommand3 = new DelegateCommand(Test3);
            TestCommand4 = new DelegateCommand(Test4);
        }

        /// <summary>
        /// 指的是Lily断连
        /// </summary>
        private void Test()
        {
         
            this.websocket.CancelLily(0);
        }
        private void Test2()
        {
            this.websocket.CancelLily(1);
        }

        private void Test3()
        {

            this.websocket.CancelLxwServer(0);
        }
        private void Test4()
        {
            this.websocket.CancelLxwServer(1);
        }

        /// <summary>
        /// 收藏下单（当前券号、tick图日、还有量）
        /// </summary>
        private void ToggleFavouriteHandle()
        {
            // 处理收藏逻辑
            if (IsFavourite)
            {
                // 收藏逻辑，例如保存到数据库或记录
                SaveFavourite();
            }
            else
            {
                // 取消收藏逻辑，例如从数据库中删除记录
                RemoveFavourite();
            }
        }

        /// <summary>
        /// 移除券码为 当前券码的收藏
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void RemoveFavourite()
        {
        }

        /// <summary>
        /// 增加一则收藏
        /// </summary>
        private void SaveFavourite()
        {
            //string ConfigFilePath = MainViewModel.ConfigFilePath;
            //// 读取现有配置
            //WindowConfig existingConfig = null;
            //if (File.Exists(ConfigFilePath))
            //{
            //    string existingJson = File.ReadAllText(ConfigFilePath);
            //    existingConfig = JsonConvert.DeserializeObject<WindowConfig>(existingJson);
            //}
            //var newWindowPosition = new WindowPosition
            //{
            //    Top = CurrentWindow.Top,
            //    Left = CurrentWindow.Left,
            //    Width = CurrentWindow.ActualWidth,
            //    Height = CurrentWindow.ActualHeight,
            //    TsCode = currentTsCode,
            //    CbDays = CurrentCbDays,
            //    IsFavourite = true // 设为收藏
            //};
            //// 如果没有现有配置，则初始化一个新的配置对象
            //if (existingConfig == null)
            //{
            //    existingConfig = new WindowConfig
            //    {
            //        WindowPositions = new Dictionary<string, List<WindowPosition>>()
            //    };
            //}

            //// 确保 "OrderView" 键存在
            //if (!existingConfig.WindowPositions.ContainsKey("OrderView"))
            //{
            //    existingConfig.WindowPositions["OrderView"] = new List<WindowPosition>();
            //}

            //// 查找现有的 TsCode 条目
            //var orderViewPositions = existingConfig.WindowPositions["OrderView"];
            //var existingPosition = orderViewPositions.FirstOrDefault(p => p.TsCode == this.BondNumber);

            //if (existingPosition != null)
            //{
            //    // 如果 TsCode 存在，覆盖现有条目
            //    orderViewPositions.Remove(existingPosition);
            //}
            //// 新增条目
            //orderViewPositions.Add(newWindowPosition);

            //// 将更新后的配置序列化为 JSON 字符串
            //string json = JsonConvert.SerializeObject(existingConfig, Formatting.Indented);

            //// 保存到文件
            //File.WriteAllText(ConfigFilePath, json);

            //// 记录日志和显示成功消息
            //MessageBox.Show("窗口位置已保存为收藏！");
        }

        private void SelectedBidHandle(BidHistory history)
        {
            if (history == null)
            {
                return;
            }
            string bidType = history.BidType.ToString();
            decimal price = history.Price;
            decimal totalVolume = history.TotalVolume;
            string tsCode = history.TsCode;

            this.IsSellChecked = bidType == "Bid" ? true : false;
            this.IsBuyChecked = bidType == "Bid" ? false : true;
            this.BondNumber = tsCode;
            this.OrderPrice = price;

            if (OccupiedBroker != null && OccupiedBroker.Count == 1)
            {
                this.SelectedReceiver = ChatReceivers
    .Where(o => o.Brokerid == OccupiedBroker[0].BrokerId && o.IsDisabled == false)
    .FirstOrDefault() ?? ChatReceivers[0];
                return;
            }
            this.SelectedReceiver = ChatReceivers
    .Where(o => o.Company == history.BrokerName && o.IsDisabled == false)
    .FirstOrDefault() ?? ChatReceivers[0];
        }


        private void SelectedTradeHandle(TradeHistoryRow history)
        {
            if (history == null || OrderListViewModel.IsQiangPing)
            {
                return;
            }
            //string bidType = history.BidType.ToString();
            decimal price = history.TradePrice;
            decimal totalVolume = history.Volume;
            string tsCode = history.TsCode;

            //this.IsSellChecked = bidType == "Bid" ? true : false;
            //this.IsBuyChecked = bidType == "Bid" ? false : true;

            PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            {
                this.BondNumber = tsCode;
                this.OrderPrice = price;
                //if (OccupiedBroker != null)
                //{
                //    return;
                //}
                this.SelectedReceiver = ChatReceivers
        .Where(o => o.Company == history.BrokerName && o.IsDisabled == false)
        .FirstOrDefault() ?? ChatReceivers[0];
            });

        }

        private bool isTopMost = false;

        public bool IsTopMost
        {
            get { return isTopMost; }
            set { isTopMost = value; RaisePropertyChanged(); }
        }

        private void SetTopMostWindow()
        {
            // 获取当前窗口并置顶
            var currentWindow = PrismApplication.Current.Windows.OfType<System.Windows.Window>().SingleOrDefault(w => w.IsActive);
            if (currentWindow != null)
            {
                IsTopMost = !IsTopMost;
                currentWindow.Topmost = IsTopMost;
            }
        }

        public static DefaultTradingVolumeView _defaultTradingVolumeView; // 声明一个私有字段存储单例

        private async void OpenDefaultTradingVolumeView()
        {
            if (_defaultTradingVolumeView == null)
            {
                _defaultTradingVolumeView = new DefaultTradingVolumeView
                {
                    Title = $"{UserHelper.NickName}+默认交易量",
                    WindowStartupLocation = WindowStartupLocation.CenterScreen // 设置窗口启动位置为屏幕中央
                };

                //await Task.Run(() =>
                //{
                //    // 模拟一些需要后台执行的初始化操作
                //    System.Threading.Thread.Sleep(100); // 模拟延迟
                //});

                _defaultTradingVolumeView.Show();
            }
            else
            {
                // 如果窗口已经显示，则检查窗口状态
                if (_defaultTradingVolumeView.WindowState == WindowState.Minimized)
                {
                    // 如果窗口最小化，则先将其恢复正常状态
                    _defaultTradingVolumeView.WindowState = WindowState.Normal;
                }

                // 然后再将窗口置顶显示
                _defaultTradingVolumeView.Activate(); // 激活置顶
            }
        }

        /// <summary>
        /// 根据是否远期刷新一下界面
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void RefreshDataByForward()
        {
            AppLog.WriteInfo($"是否远期，点击{(this.IsForward ? "远期" : "近期")}");

            PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            {
                if (!string.IsNullOrEmpty(this.BondNumber))
                {

                    OnTsSelectionChangedAsync(this.BondNumber, false);

                    //UpdateFilterTrades();
                    //OnCbDaysChanged();tes
                }
            });

            MessageBox.Show("刷新界面，当前展示的是券码为" + (this.BondNumber) + "的" + (this.IsForward == true ? "远期" : "非远期") + "数据。");
        }

        /// <summary>
        /// 获取最新价
        /// </summary>
        private async void GetLatestPrice()
        {
            DateOnly dtEnd = DateOnly.FromDateTime(DateTime.Now);

            DateOnly dtStart = dtEnd.AddDays(-1);
            //var temp = UserHelper.GetTradeHistories(this.BondNumber, dtStart, dtEnd);
            if (Trades.Count > 0)
            {

                //var temp = UserHelper.GetTradeHistories(this.BondNumber, dtStart, dtEnd);
                PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                {
                    OrderPrice = Trades.LastOrDefault().TradePrice;
                });
                //PrismApplication.Current.Dispatcher.Invoke(() =>
                //{
                //    Random r = new Random();
                //    long a = r.NextInt64(10);
                //    Trades.Add(new TradeHistoryRow() { TradeDate = DateTime.Now, TradePrice = a });
                //});
            }
        }

        /// <summary>
        /// 改价(根据券码）
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        //private void ChangePrice(string obj)
        //{
        //    (PrismApplication.Current.MainWindow as OrderView)?.Close();
        //    UserTrade t = OrderListViewModel.StaticTradeList.Where(x => x.TsCode == BondNumber).OrderByDescending(x => x.Time).FirstOrDefault();
        //    if (t != null)
        //    {
        //        ChangePriceView frm = new ChangePriceView();
        //        frm.ShowDialog();

        //        if (t.Status != 0 & t.Status != 1 & t.Status != 4)
        //        {
        //            Growl.WarningGlobal("该单无法改价");
        //            return;
        //        }

        //    }
        //    else
        //    {
        //        Growl.WarningGlobal("请检查券码和交易内容");
        //    }
        //}

        /// <summary>
        /// 重定向改价(根据lily发来的）
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private async void RedirectChangePrice(string changePriceTradeIds)
        {
            try
            {
                // 去掉方括号和换行符
                string cleanedString = changePriceTradeIds.Replace("[", "").Replace("]", "").Replace("\\r\\n", "").Trim();

                // 将清理后的字符串分割成数组
                string[] tradeIdArray = cleanedString.Split(',');

                //var tradelist = _dailyData.GetUserTrades();
                var tradesNew = await Task.Run(() => UserHelper.FindAllXunJiaOrdersAsync());

                MessageBox.Show("注意这个操作是重定向到改价窗口,需要改价个数为" + tradeIdArray.Count());
                foreach (string tradeIdString in tradeIdArray)
                {
                    var userTrade = tradesNew.Where(x => x.UserTradeId == int.Parse(tradeIdString)).FirstOrDefault();

                    UserTrade newTrade = null;

                    if (userTrade != null)
                    {
                        newTrade = new UserTrade
                        {
                            // 根据需要设置 UserTrade 对象的属性
                            // 例如：
                            BrokerID = userTrade.BrokerId,
                            Status = userTrade.Status,
                            Price = (decimal)userTrade.Price,
                            Volume = int.Parse(userTrade.Volume),
                            OnHoldVolume = int.Parse(userTrade.RestVolume),
                            TsCode = userTrade.Tscode,
                            Time = userTrade.CreateTime,
                            DealType = userTrade.Direction == "bond_0" ? "买入" : (userTrade.Direction == "bond_1" ? "卖出" : "未知"), // 根据Direction设置DealType
                            UserTradeID = userTrade.UserTradeId,
                            ChannelID = userTrade.ChannelId,
                            DeliveryDate = DateOnly.FromDateTime(userTrade.DeliveryTime),
                            DeliverySpeed = userTrade.DeliverySpeed,
                            Target = userTrade.Target
                            // 其他属性赋值
                        };

                        if (newTrade != null)
                        {
                            if (newTrade.Status != 0 && newTrade.Status != 1 && newTrade.Status != 4 && newTrade.Status != 7)
                            {
                                Growl.Warning("该单无法改价，当前状态为：" + newTrade.StatusText, MsgToken);
                                continue;
                            }

                            this.redirectUserTrade = newTrade;
                            var viewModel = new ChangePriceViewModel(newTrade);
                            viewModel.ChangePriceRequested -= ChangePriceRedirect;
                            viewModel.ChangePriceRequested += ChangePriceRedirect;
                            // 查找当前活动窗口
                            var activeWindow = PrismApplication.Current.Windows.OfType<OrderView>().FirstOrDefault(w => w.IsActive);
                            var parentWindow = activeWindow;

                            // 创建新窗口并设置DataContext
                            var window = new ChangePriceView
                            {
                                DataContext = viewModel,
                                Owner = parentWindow, // 设置父窗口
                                WindowStartupLocation = WindowStartupLocation.CenterOwner // 设置窗口启动位置为父窗口中心
                            };
                            window.ShowDialog();
                        }
                        else
                        {
                            Growl.Warning("请检查券码和交易内容", MsgToken);
                        }
                    }
                    //UserTrade userTrade = tradelist.Where(x => x.UserTradeID == int.Parse(tradeIdString)).FirstOrDefault();
                    //if (userTrade != null)
                    //{


                    //    if (userTrade.Status != 0 & userTrade.Status != 1 & userTrade.Status != 4)
                    //    {
                    //        Growl.WarningGlobal("该单无法改价"+"当前状态为："+userTrade.StatusText);
                    //        return;
                    //    }

                    //    this.redirectUserTrade = userTrade;
                    //    var viewModel = new ChangePriceViewModel(userTrade);
                    //    viewModel.ChangePriceRequested -= ChangePrice;
                    //    viewModel.ChangePriceRequested += ChangePrice;
                    //    var parentWindow = PrismApplication.Current.MainWindow;

                    //    // 创建新窗口并设置DataContext
                    //    var window = new ChangePriceView
                    //    {
                    //        DataContext = viewModel,
                    //        Owner = parentWindow, // 设置父窗口
                    //        WindowStartupLocation = WindowStartupLocation.CenterOwner // 设置窗口启动位置为父窗口中心
                    //    };
                    //    window.ShowDialog();

                    //}
                    //else
                    //{
                    //    Growl.WarningGlobal("请检查券码和交易内容");
                    //}
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("改价重定向异常！" + ex.Message);
            }

        }
        private UserTrade redirectUserTrade = null; // 

        /// <summary>
        /// 重定向改价界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ChangePriceRedirect(object? sender, ChangePriceArgs e)
        {
            try
            {
                var newTrade = e.Trade;
                if (await SendModify(redirectUserTrade, newTrade))
                {
                    AppLog.WriteInfo("改价操作，sendModify成功!" + newTrade.ToString());
                    //MessageBox.Show("改价成功");
                }
                else
                {
                    MessageBox.Show("改价失败");
                    AppLog.WriteError("改价失败：");
                }

            }
            catch (Exception ex)
            {
                AppLog.WriteError("改价异常：" + ex.StackTrace + ex.Message);
            }

        }





        private async Task<bool> SendModify(UserTrade olduserTrade, UserTrade newuserTrade)
        {

            //string order = $"{olduserTrade.DealType} {olduserTrade.TsCode.Replace(".IB", "")} 改 {newuserTrade.Price}";
            //var result = MessageBox.Show("是否改价？ \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            //if (result == MessageBoxResult.No)
            //{
            //    blocking = false;
            //    AppLog.WriteInfo("用户取消改价了");
            //    return false;
            //}
            if(Trades==null||Trades.Count==0)
            {
                AppLog.WriteWarn($"{this.BondNumber}无成交，无法下单");
                Growl.Warning($"{this.BondNumber}无成交，无法下单",MsgToken);

                return false;
            }
            string order = $"{olduserTrade.DealType} {olduserTrade.TsCode.Replace(".IB", "")} 价格 改 {newuserTrade.Price} ,量改{newuserTrade.Volume}";
            //decimal CurrentPrice = _dailyData.GetLatestPrice(TsInfo, false);
            decimal CurrentPrice = Trades.LastOrDefault().TradePrice;
            string orderDeliveryInfo = olduserTrade.DealType;
            if (orderDeliveryInfo == "买入") //买单，所以改-现在必须>0.25
            {
                if (CurrentPrice - newuserTrade.Price > 0.0025M)
                {
                    var result6 = MessageBox.Show("是否确认改价？当前是买单---当前价差超过0.25BP \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

                    if (result6 == MessageBoxResult.No)
                    {
                        blocking = false;
                        AppLog.WriteInfo("用户取消改价了");
                        return false;
                    }
                }
                else
                {
                    var result2 = MessageBox.Show("是否改价？ \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result2 == MessageBoxResult.No)
                    {
                        blocking = false;
                        AppLog.WriteInfo("用户取消改价了");
                        return false;
                    }
                }
            }
            else if (orderDeliveryInfo == "卖出")
            {
                if (newuserTrade.Price - CurrentPrice > 0.0025M)
                {
                    var result3 = MessageBox.Show("是否确认改价？当前是卖单---当前价差超过0.25BP \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result3 == MessageBoxResult.No)
                    {
                        blocking = false;
                        AppLog.WriteInfo("用户取消改价了");
                        return false;
                    }
                }
                else
                {
                    var result4 = MessageBox.Show("是否改价？ \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result4 == MessageBoxResult.No)
                    {
                        blocking = false;
                        AppLog.WriteInfo("用户取消改价了");
                        return false;
                    }
                }
            }
            QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
            CurrentGuid = Guid.NewGuid();
            qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.ChangePrice;
            //QCT.Command = order;
            //QCT.Price = newuserTrade.Price;

            newuserTrade.ChatID = UserHelper.UserID.ToString();
            qsr.Trade = newuserTrade;
            qsr.Guid = CurrentGuid;
            qsr.Token = UserHelper.Token;

            string msg;
            try
            {
                if (bIsConnected)
                {
                    //bResponseReceived = false;
                    //clientWebsocket.SendResponseToServer(qsr);
                    //IsLoading = true;
                    //Task.Run(() =>
                    //{
                    //    WaitingResponseThread();
                    //});

                    bResponseReceived = false;
                    blocking = true;
                    IsLoading = true;
                    LoadingMessage = "正在发送改价指令...";
                    websocket.SendResponseToServer(qsr);
                    await WaitForWebSocketResponse(); // 等待 WebSocket 响应

                    IsLoading = false;
                    blocking = false;
                    LoadingMessage = "发送成功!";
                }
                else
                {
                    Growl.Error("连接失败，请检查", MsgToken);
                    blocking = false;
                    AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
                    return false;
                }
            }
            catch
            {
                MessageBox.Show("无法连接服务器，请联系管理员！", "Error");
                AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
                return false;
            }
            return false;

            //var result1 = MessageBox.Show("中介是否允许改价？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            //if (result1 == MessageBoxResult.No)
            //{
            //    blocking = false;
            //    QCT.Price = olduserTrade.Price;
            //    AppLog.WriteInfo($"中介拒绝改价,{QCT.Command},{QCT.Target}" + olduserTrade.UserTradeID.ToString());
            //    return false;
            //}
            //else
            //{
            //    CurrentGuid = Guid.NewGuid();
            //    qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.ChangePriceConfirm;
            //    qsr.Code = 0;
            //    qsr.Trade = newuserTrade;
            //    qsr.Token = UserHelper.Token;
            //    qsr.Guid = CurrentGuid;
            //}


            //try
            //{
            //    if (bIsConnected)
            //    {
            //        bResponseReceived = false;
            //        blocking = true;
            //        IsLoading = true;
            //        LoadingMessage = "正在发送确认改价指令...";
            //        websocket.SendResponseToServer(qsr);
            //        await WaitForWebSocketResponse(); // 等待 WebSocket 响应

            //        IsLoading = false;

            //        LoadingMessage = "发送成功!";
            //        blocking = false;
            //    }
            //    else
            //    {
            //        blocking = false;
            //        MessageBox.Show("无法连接发送服务器，请联系管理员");
            //        AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
            //        return false;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    blocking = false;
            //    Growl.ErrorGlobal("无法连接服务器，请联系管理员！" + ex.Message);
            //    //MessageBox.Show("无法连接发送服务器，请联系管理员");
            //    AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
            //    return false;
            //}
            //return true;
        }
        /// <summary>
        /// 快捷键触发
        /// </summary>
        /// <param name="obj"></param>
        private void OnShortCutTriggered(string keyValue)
        {
            switch (keyValue)
            {
                case "Enter":
                    //PlaceAnOrder();
                    break;
                case "Esc":
                    CancelOrder();
                    break;

                case "SaveConfig":
                    SaveConfig();
                    break;
                case "F1":
                    this.IsBuyChecked = true;
                    this.IsSellChecked = false;
                    PlaceAnOrder();
                    break;
                case "F2":
                    this.IsSellChecked = true;
                    this.IsBuyChecked = false;
                    PlaceAnOrder();
                    break;

            }
        }

        private void SaveConfig()
        {
            Growl.InfoGlobal("该功能尚在开发中，请稍候...");
            return;
        }

        List<UserTrade> AllSuccessPlaceOrders = new List<PlaceOrder_Shared.Models.Common.UserTrade>(); // 保存这个页面所有下单成功的单
        /// <summary>
        /// Esc键触发回撤指令
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public async void CancelOrder()
        {
            //UserTrade t = OrderListViewModel.StaticTradeList.Where(x => x.TsCode == this.BondNumber).OrderByDescending(x => x.Time).FirstOrDefault();
            if (this.BondNumber == null)
            {
                Growl.Warning("请选中券码再撤单", MsgToken);
                return;
            }

            if (blocking == true)
            {
                Growl.Warning("有正在执行的任务，请稍后...", MsgToken);
                return;
            }
            //if (AllSuccessPlaceOrders == null|| AllSuccessPlaceOrders.Count == 0)
            //{
            //    Growl.WarningGlobal("未曾下过单，无法撤单");
            //    return;
            //}
            if(IsLoading)
            {
                Growl.Warning("有正在执行的任务，无法撤单", MsgToken);
                return;
            }
            blocking = true;
            //var tradesNew = UserHelper.FindKeCheXunJiaOrdersAsync().Result;
            //var tradeModels = tradesNew.Select(trade => new UserTrade
            //{
            //    // 根据需要设置 UserTrade 对象的属性
            //    // 例如：
            //    BrokerID = trade.BrokerId,
            //    Status = trade.Status,
            //    Price = (decimal)trade.Price,
            //    Volume = (int.Parse)(trade.Volume),
            //    OnHoldVolume = (int.Parse)(trade.RestVolume),
            //    TsCode = trade.Tscode,
            //    Time = trade.CreateTime,
            //    DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"), // 根据Direction设置DealType
            //    UserTradeID = trade.UserTradeId,
            //    ChannelID = trade.ChannelId,
            //    DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
            //    DeliverySpeed = trade.DeliverySpeed,
            //    Target = trade.Target
            //    // 其他属性赋值
            //}).ToList();
            //var TradeList = tradeModels.ToObservableCollection();
            //UserTrade t = TradeList.Where(o => o.TsCode == this.BondNumber).OrderByDescending(o => o.Time).FirstOrDefault();

            UserTrade t = await UserHelper.LoadTradesAndFindLatestAsync(this.BondNumber);
            //UserTrade t = AllSuccessPlaceOrders.Where(o => o.TsCode == this.BondNumber).LastOrDefault(); // 改逻辑，esc撤 下的最近一笔成功的单子
            //UserTrade t = _dailyData.GetUserTrades().Where(x => x.TsCode == this.BondNumber).OrderByDescending(x => x.Time).FirstOrDefault();
            if (t == null)
            {
                Growl.Warning($"该单无法撤单,找不到-券码{this.BondNumber}的单子", MsgToken);
                blocking = false;
                return;
            }
            if (t != null)
            {
                if (t.Status == 3 || t.Status == 5)
                {
                    MessageBox.Show($"该单{t.TsCode},价格：{t.Price},询量：{t.Volume}-状态不对，无法撤单", "Error");
                    blocking = false;
                    return;
                }


                // 在需要显示消息框的地方调用该方法
                string type = string.Empty;
                if (t.DealType == "bid" || t.DealType == "买入")
                {
                    type = "买";
                }
                else if (t.DealType == "ofr" || t.DealType == "卖出")
                {
                    type = "卖";

                }
                var result = HandyControl.Controls.MessageBox.Show(
                    $"是否撤单？当前是{type}单！ \r\n券号:{t.TsCode}\r\n价格:{t.Price}\r\n询量:{t.Volume}\r\n剩余询量：{t.OnHoldVolume}\r\n交割日:{t.DeliveryDate:yyyy-MM-dd} \r\n下单时间:{t.Time}。",
                    "撤单确认！",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (result == MessageBoxResult.No)
                {
                    blocking = false;
                    return;
                }


                CurrentGuid = Guid.NewGuid();
                OrderListViewModel.CurrentGuid = CurrentGuid;
                UserTrade trade = new UserTrade();
                trade.Command = "ref";
                trade.ChatID = OrderListViewModel.ChatReceivers.Where(o => o.Brokerid == t.BrokerID).FirstOrDefault().ChatId;
                trade.Target = t.Target;
                QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
                qsr.UserID = UserHelper.UserID;
                qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.Withdraw;
                qsr.Guid = CurrentGuid;
                qsr.Trade = t;
                qsr.Guid = CurrentGuid;
                qsr.RoleType = 0;
                qsr.Trade.UserID = UserHelper.UserID;
                qsr.Trade.ChatID = UserHelper.UserID.ToString();
                try
                {

                    if (bIsConnected)
                    {
                        //websocket.SendResponseToServer(qsr);
                        // 显示加载对话框并等待 WebSocket 响应
                        // 显示加载对话框并等待 WebSocket 响应
                        bResponseReceived = false;
                        blocking = true;
                        IsLoading = true;
                        LoadingMessage = "正在发送初次撤单指令...";
                        websocket.SendResponseToServer(qsr);
                        await WaitForWebSocketResponse(); // 等待 WebSocket 响应

                        IsLoading = false;

                        LoadingMessage = "发送成功!";
                    }
                    else
                    {
                        Growl.Error("服务器未连接,请检查", MsgToken);
                        AppLog.WriteError($"撤单：微信撤单失败,{t.Command},{t.Target}");
                        blocking = false;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("无法连接服务器，请联系管理员！", "Error");
                    AppLog.WriteError($"撤单：微信撤单失败,{t.Command},{t.Target}", t.UserTradeID.ToString());
                    blocking = false;
                    return;
                }
                finally
                {
                    blocking = false;
                }
                //// 在需要显示消息框的地方调用该方法
                //var result2 = HandyControl.Controls.MessageBox.Show(
                //    $"中介是否允许撤单？\r\n券号:{t.TsCode}\r\n价格:{t.Price}\r\n询量:{t.Volume}\r\n交割日:{t.DeliveryDate:yyyy-MM-dd}",
                //    "确认",
                //    MessageBoxButton.YesNo,
                //    MessageBoxImage.Question);

                //if (result2 == MessageBoxResult.No)
                //{
                //    AppLog.WriteError($"撤单：中介拒绝撤单,{t.Command},{t.Target}", t.UserTradeID.ToString());
                //    return;
                //}
                //try
                //{
                //    qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.Withdrawed;
                //    bResponseReceived = false;

                //    IsLoading = true;
                //    LoadingMessage = "正在发送确认撤单指令...";
                //    bResponseReceived = false;
                //    websocket.SendResponseToServer(qsr);
                //    await WaitForWebSocketResponse(); // 等待 WebSocket 响应

                //    IsLoading = false;
                //    //Task.Factory.StartNew(() =>
                //    //{
                //    //    frmProgress.bClose = false;
                //    //    WaitingResponseThread();
                //    //    frmProgress.bClose = true;
                //    //});
                //    //using (frmProgress frm = new frmProgress())
                //    //{
                //    //    frm.ShowDialog();
                //    //}
                //    LoadingMessage = "发送第二次撤单成功!";
                //    //websocket.SendResponseToServer(qsr);
                //    //Task.Factory.StartNew(() =>
                //    //{
                //    //    frmProgress.bClose = false;
                //    //    WaitingResponseThread();
                //    //    frmProgress.bClose = true;
                //    //});
                //    //using (frmProgress frm = new frmProgress())
                //    //{
                //    //    frm.ShowDialog();
                //    //}
                //}
                //catch
                //{
                //    MessageBox.Show("撤单失败", "异常");
                //}

                //MessageBox.Show("撤单完成", "信息");
                //t.Status = 5;
                //AppLog.WriteError($"撤单：成功,{t.Command},{t.Target}" + t.UserTradeID.ToString());
                OrderListViewModel.UpdateFlag = true;
            }

        }

        private decimal LimitBP1 = 0.01M;
        private decimal LimitBP2 = 0.005M;

        /// <summary>
        /// 回车键触发下单指令
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public async void PlaceAnOrder()
        {
            DateTime now = DateTime.Now;

            //判断是否在交割日期范围内
            if(CheckIfDeliveryDateInHolidays())
            {
                Growl.Warning("不在规定的交割日期内，请选择合适的询清算速度", MsgToken);
                return;
            }
            // 判断是否为当天并且时间超过 10:30 AM
            if (Trades == null || Trades.Count == 0)
            {
                Growl.Warning("没有交易，无法下单", MsgToken);
                return;
            }
            if (DeliveryDate.Date == now.Date && now.TimeOfDay > new TimeSpan(10, 30, 0))
            {
                // 日期加 1
                AppLog.WriteWarn("超过当日十点半不能做当日单子！");
                Growl.Warning("超过当日十点半不能做当日单子！", MsgToken);
                //GetDeliveryDate();
                return;
            }
            if (SelectedReceiver == null)
            {
                Growl.Warning("请选择中介", MsgToken); 
                return;
            }


      
            if (!bIsConnected)
            {
                Growl.Warning("服务器已断开，请联系管理员！", MsgToken);
                AppLog.WriteError("服务器已断开，请联系管理员！");
                return;
            }
            if(IsLoading)
            {
                Growl.Warning("有正在执行的任务，无法下单", MsgToken);
                AppLog.WriteError("有正在执行的任务，无法下单");
                return;
            }
            if (VolumeValue == 0M)
            {
                Growl.Warning("下单量为0，请修改。", MsgToken);
                return;
            }
            if (VolumeValue < 2000M)
            {
                Growl.Warning("下单量不足2000，请修改", MsgToken);
                return;
            }
            if (volumeValue % 1000 != 0)
            {
                Growl.Warning("下单量只能是1000倍数，请修改", MsgToken);
                return;
            }
            if (string.IsNullOrEmpty(BondNumber))
            {
                Growl.Warning("请选中券码。", MsgToken);
                return;
            }
            if (string.IsNullOrEmpty(Target))
            {
                Growl.Warning("请选中接收人!", MsgToken);
                return;
            }
            if (TsInfo == null)
            {
                Growl.Warning("未选择券码，请检查", MsgToken);
                return;
            }
            int MaxVolume = IsBuyChecked ? UserHelper.TradeLimit.MaxBidVolume : UserHelper.TradeLimit.MaxOfrVolume;
            decimal CurrentPrice = 0M;
            if (Trades.Count > 0)
            {
                CurrentPrice = Trades.LastOrDefault().TradePrice;
            }
            else
            {
                Growl.Warning($"{this.BondNumber}无成交，无法下单！",MsgToken);
                return;
                //CurrentPrice = _dailyData.GetLatestPrice(TsInfo, false);
            }
            //CurrentPrice = _dailyData.GetLatestPrice(TsInfo, false);
            if (IsBuyChecked)
            {
                if (this.VolumeValue > MaxBidVolume)
                {
                    if (MaxBidVolume == 0)
                    {
                        AppLog.WriteWarn("最大买量为0，无法下买单!");
                        Growl.Warning("最大买量为0，无法下买单!", MsgToken);
                        return;
                    }
                    else
                    {
                        AppLog.WriteWarn($"当前下单量超过最大买量，最大只能下{MaxBidVolume}");
                        Growl.Warning($"当前下单量超过最大买量，最大只能下{MaxBidVolume}", MsgToken);
                    }
                    VolumeValue = MaxBidVolume;
                }
                if (CurrentPrice - OrderPrice > 0.01M)
                {
                    Growl.Warning("下单价与当前最优价负向偏离1BP，不允许下单！", MsgToken);
                    return;
                }
                if (CurrentPrice - OrderPrice > 0.0025M)
                {
                    var result1 = MessageBox.Show("下单买价与当前价差超过0.25BP，是否下买单", "确认---买单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result1 == MessageBoxResult.Yes)
                    {
                        // 用户点击了"是"
                        // 执行下单操作

                    }
                    else
                    {
                        return;
                    }
                }
                //if (!CheckIfInBestPriceRange(this.Ofrs.ToList(), false, LimitBP1))
                //{

                //    //Growl.WarningGlobal("下单价与当前最优价负向偏离1BP，不允许下单！");
                //    return;
                //    //var result1 = MessageBox.Show("下单买价与当前价差超过1BP，不允许下买单", "确认---买单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
                //    //if (result1 == MessageBoxResult.Yes)
                //    //{
                //    //    // 用户点击了"是"
                //    //    // 执行下单操作
                //    //    return;

                //    //}
                //    //else
                //    //{
                //    //    return;
                //    //}
                //}
                //if (!CheckIfInBestPriceRange(this.Ofrs.ToList(), false, LimitBP2))
                //{
                //    var result1 = MessageBox.Show("下单买价与当前价差超过0.25BP，是否下买单", "确认---买单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
                //    if (result1 == MessageBoxResult.Yes)
                //    {
                //        // 用户点击了"是"
                //        // 执行下单操作

                //    }
                //    else
                //    {
                //        return;
                //    }
                //}

            }
            else
            {
                if (this.VolumeValue > MaxOfrVolume)
                {
                    if (MaxOfrVolume == 0)
                    {
                        AppLog.WriteWarn("最大卖量为0，无法下卖单!");
                        Growl.Warning("最大卖量为0，无法下卖单!", MsgToken);
                        return;
                    }
                    else
                    {
                        AppLog.WriteWarn($"当前下单量超过最大卖量，最大只能下{MaxOfrVolume}");
                        Growl.Warning($"当前下单量超过最大卖量，最大只能下{MaxOfrVolume}", MsgToken);
                    }
                    VolumeValue = MaxOfrVolume;
                }

                if (OrderPrice - CurrentPrice > 0.01M)
                {
                    Growl.Warning("下单价与当前最优价负向偏离1BP，不允许下单！",MsgToken);
                    return;
                }
                if (OrderPrice -CurrentPrice  > 0.0025M)
                {
                    var result1 = MessageBox.Show("下单卖价与当前价差超过0.25BP，是否下买单", "确认---买单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result1 == MessageBoxResult.Yes)
                    {
                        // 用户点击了"是"
                        // 执行下单操作

                    }
                    else
                    {
                        return;
                    }
                }
                //if (!CheckIfInBestPriceRange(this.Bids.ToList(), true, LimitBP1))
                //{


                //    return;

                //}
                //if (!CheckIfInBestPriceRange(this.Bids.ToList(), true, LimitBP2))
                //{
                //    var result1 = MessageBox.Show("下单卖价与当前价差超过0.25BP，是否下卖单", "确认---卖单！", MessageBoxButton.YesNo, MessageBoxImage.Question);
                //    if (result1 == MessageBoxResult.Yes)
                //    {
                //        // 用户点击了"是"
                //        // 执行下单操作

                //    }
                //    else
                //    {
                //        return;
                //    }
                //}

            }

            string order = string.Empty;
            //QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
            qsr = new QuanYiOrderServerResponseClass();
            UserTrade trade = new UserTrade();

            if (IsBuyChecked)
            {
                if (TotalBids.Ofrs == null)
                {
                    Growl.Warning("无买单，请修改。", MsgToken);
                    return;
                }
                string formattedDate = this.DeliveryDate.ToString("M月d日");
                trade.DeliverySpeedFormat = formattedDate +" "+ (SelectedOptionJia0 ? "+0" : "+1");

                trade.DealType = "bid";
                trade.OrderType = UserTrade.UserTradeOrderTypeEnum.Bid;

                if(SelectedOptionJia0)
                {
                    trade.DeliverySpeed = "0";
                }
                else
                {
                    trade.DeliverySpeed = "1";
                }
                
                order = order + "bid ";
                //0705改
                //if (TotalBids.Ofrs.Count(x => x.Price == OrderPrice) == 0)
                //{
                //    trade.DealType = "bid";
                //    trade.OrderType = UserTrade.UserTradeOrderTypeEnum.Bid;
                //    order = order + "bid ";
                //}
                //else
                //{
                //    trade.DealType = "taken";
                //    trade.OrderType = UserTrade.UserTradeOrderTypeEnum.Bid;
                //    order = order + "taken ";
                //}
            }
            else
            {
                if (TotalBids.Ofrs == null)
                {
                    Growl.Warning("无卖单，请修改。", MsgToken);
                    return;
                }
                if (SelectedOptionJia0)
                {
                    trade.DeliverySpeed = "0";
                }
                else
                {
                    trade.DeliverySpeed = "1";
                }
                string formattedDate = this.DeliveryDate.ToString("M月d日");
                trade.DeliverySpeedFormat = formattedDate + " " + (SelectedOptionJia0 ? "+0" : "+1");
                trade.DealType = "ofr";
                trade.OrderType = UserTrade.UserTradeOrderTypeEnum.Ofr;
                order = order + "ofr ";
                //if (TotalBids.Bids.Count(x => x.Price == OrderPrice) == 0)
                //{
                //    trade.DealType = "ofr";
                //    trade.OrderType = UserTrade.UserTradeOrderTypeEnum.Ofr;
                //    order = order + "ofr ";
                //}
                //else
                //{
                //    trade.DealType = "given";
                //    trade.OrderType = UserTrade.UserTradeOrderTypeEnum.Ofr;
                //    order = order + "given ";
                //}
            }

            string dtDate = DeliveryDate.Month.ToString() + "月" + DeliveryDate.Day.ToString() + "日";

            order = $"{order} {BondNumber.Replace(".IB", "")} {OrderPrice} {dtDate}+0 {VolumeValue / 1000}k";

            string orderType = null;
            if (IsSellChecked)
            {
                orderType = "当前是卖单";
            }
            else
            {
                orderType = "当前是买单";
            }

            //var result = MessageBox.Show($"是否下单？-- {orderType} \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            //if (result == MessageBoxResult.Yes)
            //{
            //    // 用户点击了"是"
            //    // 执行下单操作
            //    //IsLoading = true;
            //}
            //else
            //{
            //    return;
            //}
            //获取当前窗口
            // 获取当前活动的 OrderView 窗口

            CurrentGuid = Guid.NewGuid();
            bResponseReceived = false;
            AppLog.WriteInfo("SendOrder" + order);
            trade.UserID = UserHelper.UserID;
            trade.TsCode = BondNumber;
            trade.Price = OrderPrice;
            trade.Volume = (int)VolumeValue;
            trade.OnHoldVolume = trade.Volume;
            trade.DeliveryDate = DateOnly.FromDateTime(DeliveryDate);


            ChatReceiver chat = ChatReceivers.FirstOrDefault(x => x.FormattedTarget == SelectedReceiver.FormattedTarget);
            //ChatReceiver chat = ChatReceivers.Single(x => x.Target == Target);
            trade.ReceiverId = chat.Id;
            trade.ChatID = chat.ChatId;
            trade.ChannelID = chat.ChannelId;


            trade.Target = SelectedReceiver.FormattedTarget;
            trade.Guid = CurrentGuid;
            trade.Command = order;

            trade.BrokerID = chat.Brokerid;
            // if (chat==null||chat.Brokerid==-1)
            // {
            //     trade.BrokerID = null;
            // }
            //else
            // {
            //     trade.BrokerID = chat.Id;
            // }
            var currentOrderWindow = PrismApplication.Current.Windows.OfType<OrderView>().SingleOrDefault(x => x.IsActive);
            var confirmationDialog = new ConfirmationDialog(trade)
            {
                Owner = currentOrderWindow, // 设置当前 OrderView 窗口为对话框的 Owner
                WindowStartupLocation = WindowStartupLocation.CenterOwner // 确保对话框在主窗口之上
            };

            // 显示对话框并等待用户的响应
            var result = confirmationDialog.ShowDialog();

            if (result == true && confirmationDialog.IsConfirmed)
            {
                //用户点击了确认
                //执行下单操作
                IsLoading = true;
            }
            else
            {
                //用户点击了取消或者关闭了对话框
                return;
            }

            qsr.Trade = trade;
            qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.Order;
            qsr.Guid = CurrentGuid;
            int UserTradeID = 0;

            //DialogHelper.ShowLoading("开始创建询价单");
            IsLoading = true;
            LoadingMessage = "开始创建询价单...";
            await Task.Delay(20);
            string msg;
            try
            {


                if (bIsConnected)
                {
                    bResponseReceived = false;
                    //websocket.SendResponseToServer(qsr);
                    // 显示加载对话框并等待 WebSocket 响应
                    // 显示加载对话框并等待 WebSocket 响应
                    IsLoading = true;
                    LoadingMessage = "正在发送指令...";
                    websocket.SendResponseToServer(qsr); // 调用同步方法
                    await WaitForWebSocketResponse(); // 等待 WebSocket 响应

                    IsLoading = false;
                    //await DialogHelper.ShowLoadingAsync("正在发送指令", 10000, async () =>
                    //{

                    //});


                    //Task.Factory.StartNew(() =>
                    //{
                    //    WaitingResponseThread();
                    //});
                }
                else
                {
                    Status = "无法下单，请联系管理员";
                    AppLog.WriteError($"下单：微信下单失败,{trade.Command},{trade.Target}");
                    return;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"下单：下单失败,{trade.Command},{trade.Target}");
            }
            finally
            {
                IsLoading = false;
            }

            AppLog.WriteInfo($"下单：微信下单成功,{trade.Command},{trade.Target}");
            OrderListViewModel.UpdateFlag = true;
        }

        /// <summary>
        /// 判断询清算的日期是否在Holidays表里
        /// </summary>
        /// <returns></returns>
        private bool CheckIfDeliveryDateInHolidays()
        {
            try
            {

                DateTime realJiaoGeTime;

                //this.DeliveryDate = new DateTime(DateTime.Now.Year, 9, 13);
                if (SelectedOptionJia0)
                {
                    realJiaoGeTime = this.DeliveryDate;
                }else
                {
                    realJiaoGeTime = this.DeliveryDate.AddDays(1);
                }
                // 将 DateTime 转换为 DateOnly 进行比较
                DateOnly realJiaoGeDateOnly = DateOnly.FromDateTime(realJiaoGeTime);
                if (this.Holidays.Contains(realJiaoGeDateOnly))
                {
                    return true;
                }
                return false;
            } catch (Exception ex)
            {
                AppLog.WriteError("CheckIfNotInDeliveryDate异常" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 查看是否在最优对手价范围里
        /// </summary>
        /// <returns></returns>
        private bool CheckIfInBestPriceRange(List<BidHistory> bids, bool IsBuy = true, decimal limitBP = 0)
        {
            try
            {
                if (bids == null || bids.Count == 0)
                    return false;

                BidHistory bestBid = null;
                if (bids[0].Volume.Contains("+"))
                {
                    bestBid = bids[0];
                }
                else if (bids.Count > 1)
                {
                    bestBid = bids[1];
                }
                else
                {
                    Growl.Warning("摆单数量不够，无法下单！", MsgToken);
                    return false;
                }
                if (IsBuy)
                {
                    if (OrderPrice - bestBid?.Price > limitBP)
                    {
                        if (limitBP == LimitBP1)
                        {
                            Growl.Warning("下单价与当前最优价负向偏离1BP，不允许下单！", MsgToken);
                        }

                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    if (bestBid?.Price - OrderPrice > limitBP)
                    {
                        if (limitBP == LimitBP1)
                        {
                            Growl.Warning("下单价与当前最优价负向偏离1BP，不允许下单！", MsgToken);
                        }
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// ctrl + g 触发改价指令
        /// </summary>
        /// 
        /// <summary>
        /// 执行改价
        /// </summary>
        /// <summary>
        /// 执行改价
        /// </summary>
        /// 
        private UserTrade selectedChangePriceUserTrade = null;
        public void ChangePrice()
        {
            try
            {
                if (blocking)
                {
                    Growl.Warning("有正在执行的任务", MsgToken);
                    return;
                }
                if (IsLoading)
                {
                    Growl.Warning("有正在执行的任务，无法撤单", MsgToken);
                    return;
                }
                if (this.BondNumber == null)
                {
                    Growl.Info("请选中券码再改价", MsgToken);
                    return;
                }
                blocking = true;
                var tradesNew = UserHelper.FindKeCheXunJiaOrders();
                var tradeModels = tradesNew.Select(trade => new UserTrade
                {
                    // 根据需要设置 UserTrade 对象的属性
                    // 例如：
                    BrokerID = trade.BrokerId,
                    Status = trade.Status,
                    Price = (decimal)trade.Price,

                    Volume = (int.Parse)(trade.Volume),
                    OnHoldVolume = (int.Parse)(trade.RestVolume),
                    TsCode = trade.Tscode,
                    Time = trade.CreateTime,
                    DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"), // 根据Direction设置DealType
                    UserTradeID = trade.UserTradeId,
                    ChannelID = trade.ChannelId,
                    DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
                    DeliverySpeed = trade.DeliverySpeed,
                    Target = trade.Target
                    // 其他属性赋值
                }).ToList();
                var TradeList = tradeModels.ToObservableCollection();
                UserTrade userTrade = TradeList.Where(o => o.TsCode == this.BondNumber).OrderByDescending(o => o.Time).FirstOrDefault();

                //var tradesNew =  UserHelper.FindAllXunJiaOrdersAsync().Result;
                //var tradeModels = tradesNew.Select(trade => new UserTrade
                //{
                //    // 根据需要设置 UserTrade 对象的属性
                //    // 例如：
                //    BrokerID = trade.BrokerId,
                //    Status = trade.Status,
                //    Price = (decimal)trade.Price,
                //    Volume = (int.Parse)(trade.Volume),
                //    OnHoldVolume = (int.Parse)(trade.RestVolume),
                //    TsCode = trade.Tscode,
                //    Time = trade.CreateTime,
                //    DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"), // 根据Direction设置DealType
                //    UserTradeID = trade.UserTradeId,
                //    ChannelID = trade.ChannelId,
                //    DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
                //    DeliverySpeed = trade.DeliverySpeed,
                //    Target = trade.Target
                //    // 其他属性赋值
                //}).ToList();
                //var TradeList = tradeModels.ToObservableCollection();
                //UserTrade userTrade = TradeList.Where(o => o.TsCode == this.BondNumber).OrderByDescending(o => o.Time).FirstOrDefault();
                if (userTrade == null)
                {
                    AppLog.WriteWarn($"找不到券码为{this.BondNumber}的单子，无法改价");
                    Growl.Warning($"找不到券码为{this.BondNumber}的单子，无法改价", MsgToken);
                    return;
                }

                if (userTrade != null)
                {
                    selectedChangePriceUserTrade = userTrade;

                    if (userTrade.Status == 3 || userTrade.Status == 5)
                    {
                        MessageBox.Show("该单状态不对，无法改价" + userTrade.StatusText, "Error");
                        return;
                    }
                    //if (userTrade.Status != 0 & userTrade.Status != 1 & userTrade.Status != 4 & userTrade.Status != 7 & userTrade.Status != 23)
                    //{
                    //    MessageBox.Show("该单状态不对，无法改价" + userTrade.StatusText, "Error");
                    //    return;
                    //}
                }
                var viewModel = new ChangePriceViewModel(userTrade);
                viewModel.ChangePriceRequested -= ChangePrice;
                viewModel.ChangePriceRequested += ChangePrice;

                var activeWindow = PrismApplication.Current.Windows.OfType<OrderView>().FirstOrDefault(w => w.IsActive);
                var parentWindow = activeWindow;
                if (parentWindow == null)
                {
                    return;
                }
                // 创建新窗口并设置DataContext
                var window = new ChangePriceView
                {
                    DataContext = viewModel,
                    Owner = parentWindow, // 设置父窗口
                    WindowStartupLocation = WindowStartupLocation.CenterOwner, // 设置窗口启动位置为父窗口中心
                    Title = $"改价窗口,券码：{userTrade.TsCode},下单时间：{userTrade.Time.ToString() ?? "未知"}"
                };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                AppLog.WriteError("OrderViewModel+ChangePrice" + ex.Message + ex.StackTrace);
            }
            finally
            {
                this.blocking = false;
            }

        }

        private async void ChangePrice(object? sender, ChangePriceArgs e)
        {
            try
            {
                if (selectedChangePriceUserTrade == null)
                {
                    return;
                }
                UserTrade oldUserTrade = selectedChangePriceUserTrade;
                var newTrade = e.Trade;
                if (await SendModify(oldUserTrade, newTrade))
                {
                    //AppLog.WriteInfo("改价成功!"+newTrade.ToString());
                    //MessageBox.Show("改价成功");
                }
                else
                {
                    AppLog.WriteError("OrderView改价失败：");
                }

            }
            catch (Exception ex)
            {
                AppLog.WriteError("OrderView改价异常：" + ex.StackTrace + ex.Message);
            }
            finally
            {
                blocking = false;
                //this.SearchHandle();
            }

        }



        private UserTrade QCT = new UserTrade();

        private async Task WaitForWebSocketResponse()
        {
            DateTime dtStart = DateTime.Now;
            TimeSpan ts = new TimeSpan();
            ts = DateTime.Now - dtStart;

            while (ts.TotalSeconds < ClientWebSocketHelper.GlobalTimeOut)
            {
                if (bResponseReceived)
                {

                    if (GlobalQSR.Code == 0)
                    {
                        QCT.Id = GlobalQSR.Trade.Id;
                        QCT.Time = GlobalQSR.Trade.Time;
                        bWaitingforResponse = false;
                        string info = $"券码：{GlobalQSR.Trade.TsCode}" +
                            $"指令：{GlobalQSR.Trade.Command}," +
                            $"中介：{GlobalQSR.Trade.Broker}" +
                            $"类型：{GlobalQSR.Trade.DealType}," +
                            $"交割日期：{GlobalQSR.Trade.DeliveryDate}" +
                            $"询量：{GlobalQSR.Trade.Volume}" +
                            $"价格：{GlobalQSR.Trade.Price}" +
                            $"指令：{GlobalQSR.Trade.OrderType}" +
                            $"状态：{GlobalQSR.Trade.StatusText}" +
                            $"操作人：{GlobalQSR.Trade.UserName}" +
                            $"消息：{GlobalQSR.Message}";

                        if (GlobalQSR.DataType == QuanYiServerBaseClass.DataTypeEnum.Order)
                        {
                            AppLog.WriteInfo($"下单成功！{info}");
                            //AllSuccessPlaceOrders.Add(GlobalQSR.Trade);
                            Growl.Success($"下单成功！{GlobalQSR.Trade.Command}", MsgToken);
                        }

                        if (GlobalQSR.DataType == QuanYiServerBaseClass.DataTypeEnum.Withdraw || GlobalQSR.DataType == QuanYiServerBaseClass.DataTypeEnum.Withdrawed)
                        {
                            AppLog.WriteInfo($"发送撤单成功！{info}");



                            Growl.Success($"券码{this.BondNumber}的[{GlobalQSR.Trade.DealType}单]撤单成功！", MsgToken);

                        }

                        if (GlobalQSR.DataType == QuanYiServerBaseClass.DataTypeEnum.ChangePrice || GlobalQSR.DataType == QuanYiServerBaseClass.DataTypeEnum.ChangePriceConfirm)
                        {
                            AppLog.WriteInfo($"发送改价成功！{info}");
                            Growl.Success($"发送改价成功！改后价格：{GlobalQSR.Trade.Price}，改后量：{GlobalQSR.Trade.Volume}", MsgToken);
                        }
                        if (GlobalQSR.Message == null)
                        {
                            //MessageBox.Show("询价单创建失败" + info, "信息");
                            //AppLog.WriteInfo("询价单创建失败" + info);
                        }
                        else
                        {
                            //MessageBox.Show("成功!" + GlobalQSR.Message, "下单成功");
                            //Growl.SuccessGlobal("下单成功!" + GlobalQSR.Message);
                            //AppLog.WriteInfo("成功!"+GlobalQSR.Message+info);
                        }

                    }//11说明重定向到改价了 传回来一组list可能是多个改价重定向。
                    else if (GlobalQSR.Code == 11)
                    {
                        var changePriceIds = GlobalQSR.ChangePriceIds;
                        var tradeId = GlobalQSR.Trade.UserTradeID;
                        MessageBox.Show(GlobalQSR.Message, "提示");
                        var t = GlobalQSR.ChangePriceIds;
                        RedirectChangePrice(changePriceIds);
                        bWaitingforResponse = false;

                        return;
                    }
                    else
                    {
                        bWaitingforResponse = false;
                        MessageBox.Show(GlobalQSR.Message, "异常提示");
                        return;
                    }
                    bResponseReceived = false;
                    return;
                }

                await Task.Delay(20);
                ts = DateTime.Now - dtStart;
            }

            bWaitingforResponse = false;
            MessageBox.Show("连接服务器超时", "信息");
        }

        private QuanYiOrderServerResponseClass qsr;
        private void SendOrderMsgToServer()
        {
            if (bIsConnected)
            {
                bResponseReceived = false;
                websocket.SendResponseToServer(qsr);
                //Task.Factory.StartNew(() =>
                //{
                //    frmProgress.bClose = false;
                //    WaitingResponseThread();
                //    frmProgress.bClose = true;
                //});
            }
        }
        //private async void OnCbDaysChanged()
        //{
        //    // Extract day from the combo box and update legend status
        //    if (int.TryParse(Regex.Match(CbDays, @"\d+").Value, out int day))
        //    {
        //        LegendStatus = day > 1
        //            ? $"走势（最近{day}天）交易日"
        //            : $"交易走势（当日）";
        //    }
        //    else
        //    {
        //        LegendStatus = "交易走势";
        //    }

        //    if (TsInfo != null)
        //    {
        //        DateOnly dtStart = DateOnly.FromDateTime(DateTime.Now);

        //        // Calculate the start date excluding holidays
        //        while (day > 0)
        //        {
        //            dtStart = dtStart.AddDays(-1);
        //            if (!Holidays.Contains(dtStart))
        //            {
        //                day--;
        //            }
        //        }
        //        dtStart = dtStart.AddDays(1); // Increment date for the final start date

        //        // Retrieve trade histories asynchronously
        //        var tempTrades = await UserHelper.GetTradeHistoriesAsync(TsInfo.tsCode, dtStart, DateOnly.FromDateTime(DateTime.Now), !IsForward);

        //        // Use async dispatcher to update UI
        //        await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //        {
        //            lock (_tradesLock)
        //            {
        //                // Filter trades and update ObservableCollection
        //                Trades = tempTrades
        //                    .Where(o => o.TradePrice < 120 && o.TradePrice >= 0)
        //                    .ToObservableCollection() ?? new ObservableCollection<TradeHistoryRow>();
        //            }
        //        });
        //    }
        //}

        public void ChangeCbDays()
        {
            if (int.TryParse(Regex.Match(CbDays, @"\d+").Value, out int day))
            {
                LegendStatus = day > 1
                    ? $"走势（最近{day}天）交易日"
                    : $"交易走势（当日）";
            }
            else
            {
                LegendStatus = "交易走势";
            }
        }

        private object  LilyTradeApiLock = new object();
        public async void OnCbDaysChanged()
        {

            int dayCount = 0;
            if (int.TryParse(Regex.Match(CbDays, @"\d+").Value, out int day))
            {
                LegendStatus = day > 1
                    ? $"走势（最近{day}天）交易日"
                    : $"交易走势（当日）";
                dayCount = day;
            }

            else
            {
                LegendStatus = "交易走势";
            }

            if (TsInfo != null)
            {
                DateOnly dtStart = DateOnly.FromDateTime(DateTime.Now);
                int daysCount = 0;
                while (day > 0)
                {
                    dtStart = dtStart.AddDays(-1);
                    daysCount++;
                    //排除Holidays
                    if (Holidays.Contains(dtStart))
                    {
                        continue;
                    }
                    else
                    {
                        day--;
                    }
                }
                dtStart = dtStart.AddDays(1); // 将日期增加一天
                
                 var TempTrades = await UserHelper.GetTradeHistoriesAsync(TsInfo.tsCode, dtStart, DateOnly.FromDateTime(DateTime.Now), dayCount, !IsForward);
                AppLog.WriteInfo("CBDays 调用 Lily-API GetTradeHistoriesAsync");
                
                if (TempTrades == null || TempTrades.Count == 0)
                {
                    return;
                }
               
                await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                {
                  
                        Trades = TempTrades.Where(o => o.TradePrice < 120 && o.TradePrice >= 0).ToObservableCollection() ?? new ObservableCollection<TradeHistoryRow>();
                        this.MinTradePrice = Trades.Min(o => o.TradePrice) - 0.005M;
                        this.MaxTradePrice = Trades.Max(o => o.TradePrice) + 0.005M;
                        //            Trades = _dailyData.GetTradeHistoryByDate(TsInfo, dtStart, DateOnly.FromDateTime(DateTime.Now), !IsForward)?.Where(o => o.TradePrice < 120 && o.TradePrice >=0)
                        //.ToObservableCollection() ?? new ObservableCollection<TradeHistoryRow>();
                    

                });

            }
        }

        /// <summary>
        /// 买卖事件变化
        /// </summary>
        /// <param name="obj"></param>
        private void OnBuyAndSellCheckedChanged(string status)
        {
            switch (status)
            {
                case "Buy":
                    PlaceAnOrder();
                    break;
                case "Sell":
                    PlaceAnOrder();
                    break;
            }

            GetCurrentOrderStatus();
        }

        /// <summary>
        /// 当下单价格变化时触发
        /// </summary>
        private void OnOrderPriceChanged()
        {
            GetCurrentOrderStatus();
        }

        /// <summary>
        /// 当交易量变化时触发
        /// </summary>
        private void OnVolumeValueChanged()
        {
            //GetCurrentOrderStatus();
        }

        private string LastSelectedTsCode = string.Empty;
        /// <summary>
        /// 当券码改变时触发
        /// </summary>
        /// <param name="obj"></param>
        public async Task OnTsSelectionChangedAsync(string tsCode, bool IsRealTrigged = true)
        {
            try
            {
                int dayCount = 0;
                int day = int.Parse(Regex.Match(CbDays, @"\d+").Value);
                dayCount = day;
                if (LastSelectedTsCode == this.BondNumber&&IsRealTrigged == true)
                {
                    return;
                }
                LastSelectedTsCode = tsCode;
               
                if (IsRealTrigged)
                {
                    TsInfo = await UserHelper.GetBondByCode(tsCode);
                }
              

                //TsInfo = _dailyData.GetBondByCode(tsCode);
                if (TsInfo == null)
                {
                    return;
                }
                DateOnly dtStart = DateOnly.FromDateTime(DateTime.Now);
                while (day > 0)
                {
                    dtStart = dtStart.AddDays(-1);

                    //排除Holidays
                    if (Holidays.Contains(dtStart))
                    {
                        continue;
                    }
                    else
                    {
                        day--;
                    }
                }
                //DateOnly dtStart = DateOnly.FromDateTime(DateTime.Now);

                // Use await to asynchronously retrieve trade history
                //await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                //{
                //    Trades = _dailyData.GetTradeHistoryByDate(TsInfo, dtStart, DateOnly.FromDateTime(DateTime.Now), !IsForward)?
                //                        .ToObservableCollection() ?? new ObservableCollection<TradeHistoryRow>();
                //});
                dtStart = dtStart.AddDays(1); // 将日期增加一天
             
               
                var trades = await UserHelper.GetTradeHistoriesAsync(TsInfo.tsCode, dtStart, DateOnly.FromDateTime(DateTime.Now), dayCount, !IsForward);
                AppLog.WriteInfo("OnTsSelectionChangedAsync 调用Lily-API，GetTradeHistoriesAsync");
                
                //if (trades==null || trades.Count==0)
                //{
                //    return;
                //}
               
                if (trades != null&&trades.Count>0)
                {
                    PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                    {
                        this.MinTradePrice = trades.Min(o => o.TradePrice) - 0.005M;
                        this.MaxTradePrice = trades.Max(o => o.TradePrice) + 0.005M;
                    });
                    var filteredTrades = trades
               .Where(o => o.TradePrice < 120 && o.TradePrice >= 0)
               .ToObservableCollection();
                    if(Trades!=null&& Trades.Count != trades.Count)
                    {
                        Trades = filteredTrades;
                        UpdateFilterTrades();
                    }else if(Trades==null)
                    {
                        Trades = filteredTrades;

                    }

                }
                if (this.Trades!=null)
                {
                    //UpdateFilterTrades();
                    //if (trades.Count == this.Trades.Count)
                    //{
                    //    AppLog.WriteInfo($"{this.BondNumber}无需更新数据因为没变");
                    //    return;
                    //}
                    //else
                    //{
                        
                    //    AppLog.WriteInfo($"{this.BondNumber}数据变化了，原来：{this.Trades.Count}条，现在：{trades.Count}条");
                     
                    //    UpdateFilterTrades();
                    //}

                }
               
                //if(this.Trades!=null)
                //{
                //    if (trades.Count == this.Trades.Count)
                //    {
                //        AppLog.WriteInfo("没有单子无需更新");
                //        return;
                //    }
                //}

               
                //Trades = await Task.Run(() =>
                //{
                //    return UserHelper.GetTradeHistoriesAsync(TsInfo.tsCode, dtStart, DateOnly.FromDateTime(DateTime.Now), !IsForward).Result?
                //                       .Where(o => o.TradePrice < 120 && o.TradePrice >= 0).ToObservableCollection() ?? new ObservableCollection<TradeHistoryRow>();
                //    //return _dailyData.GetTradeHistoryByDate(TsInfo, dtStart, DateOnly.FromDateTime(DateTime.Now), !IsForward)?
                //    //                   .Where(o=>o.TradePrice<120&&o.TradePrice >= 0).ToObservableCollection() ?? new ObservableCollection<TradeHistoryRow>();
                //});
                if (TsInfo != null)
                {

                    

                    if (IsRealTrigged) // 表示真实触发了
                    {
                        websocket.SubscribeTradeData(TsInfo.tsCode, this.GuidStr);//这才是订阅Lily
                        AppLog.WriteInfo("OrderViewModel订阅lily——TradeData"+MsgToken);
                        if (Trades != null && Trades.Count > 0)
                        {
                            OrderPrice = Trades.LastOrDefault().TradePrice;
                        }
                        else
                        {
                            //OrderPrice = _dailyData.GetLastClosePrice(TsInfo, false); // 没有则拿最近的一条数据
                        }
                        UserTradeVolumeConfig volume=null;
                        if (OrderListViewModel.VolumeConfigs!=null)
                        {
                            volume = OrderListViewModel.VolumeConfigs.FirstOrDefault(x => x.Tscode == TsInfo.tsCode);
                        }
                         
                        if (IsRealTrigged)
                        {
                            if (volume != null)
                            {
                                VolumeValue = volume.Volume;
                            }
                            else
                            {
                                VolumeValue = 2000;
                                //volume = new UserTradeVolumeConfig() { Tscode = TsInfo.tsCode, Volume = 2000, UserId = UserHelper.UserID };
                                //_dailyData.AddUserTradeVolumeConfig(volume);
                                //OrderListViewModel.VolumeConfigs.Add(volume);
                            }


                        }

                        if (VolumeValue == 0 && MaxVolumeAccount >= 2000)
                        {
                            VolumeValue = 2000M;
                        }
                        WebSocketHelper_TradeAmountLimitEvent();
                    }

                    try
                    {
                        //var Bids = await _dailyData.GetBidHistoriesAsync(TsInfo.tsCode);
                    }
                    catch (Exception ex)
                    {
                        AppLog.WriteError("websocket抓取bids历史记录异常" + ex.StackTrace + ex.Message);
                    }

                   
                    //GetCurrentOrderStatus();
                }
            }
            catch (Exception ex)
            {
                // 在这里处理异常
                AppLog.WriteError($"处理选中Ts发生异常：{ex.Message}");
            }
        }


        /// <summary>
        /// 获取当前的下单信息
        /// </summary>
        private void GetCurrentOrderStatus()
        {
            //  string msg = null;
            //  msg += "下单：";
            //if(IsBuyChecked)
            //  {
            //      msg += "买入-" + this.BondNumber + ",";
            //  }
            //  else
            //  {
            //      msg += "卖出-"+this.BondNumber+",";
            //  }
            //  msg += "下单价格=" + this.OrderPrice+",";

            //  msg += "交易量="+this.VolumeValue;

            //  Status = msg;           
        }

        private TSInfoRow TsInfo = null; //记录当前那一条券码的信息
        private ObservableCollection<string> _tickDays;

        public ObservableCollection<string> TickDays
        {
            get => _tickDays;
            set
            {
                if (_tickDays != value)
                {
                    _tickDays = value;
                    RaisePropertyChanged();
                }
            }
        }
        private async Task InitValueAsync()
        {
            // 初始化 TickDays 示例
            TickDays = new ObservableCollection<string>
        {
            "Tick图-1天",
            "Tick图-2天",
            "Tick图-3天",
            "Tick图-4天",
            "Tick图-5天",
            "Tick图-6天",
            "Tick图-7天",
            "Tick图-8天",
            "Tick图-9天",
            "Tick图-10天"
        };



            //if(!string.IsNullOrEmpty(this.BondNumber))
            //{
            //    CheckIfInWhiteList(); //检查是否在白名单里
            //}
            //  DateOnly dtStart = DateOnly.FromDateTime(DateTime.Now);
            //  //var tradesResult = await Task.Run(() =>
            //  //    _dailyData.GetTradeHistoryByDate(TsInfo, dtStart, DateOnly.FromDateTime(DateTime.Now), true));
            //  var tradesResult = await Task.Run(() =>
            //UserHelper.GetTradeHistoriesAsync(this.BondNumber, dtStart, DateOnly.FromDateTime(DateTime.Now), true));

            //  await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            //  {
            //      Trades = tradesResult?.Where(o => o.TradePrice < 120 && o.TradePrice >= 0).ToObservableCollection() ?? new ObservableCollection<TradeHistoryRow>();



            //      StaticTsCodes = TsCodes;
            //      GetDeliveryDate();
            //  });

            PrismApplication.Current.Dispatcher.InvokeAsync(() => { GetDeliveryDate(); });
     
            SelectedReceiver = ChatReceivers[0];




        }

        // 设定比较时间为 10:30
        TimeOnly comparisonTime = new TimeOnly(10, 30, 0);

        public bool CheckIfInWhiteList()
        {
            if (this.TsCodes != null)
            {
                if (!TsCodes.Contains(this.BondNumber))
                {
                    Growl.Warning($"{this.BondNumber}不在白名单中，请检查", MsgToken);
                    this.BondNumber = null;
                    return false;
                }
            }
            return true;
        }

        private bool GetDeliveryDateOnlyOnce = false;
        private void GetDeliveryDate()
        {
            // 获取当前时间
            TimeOnly currentTime = TimeOnly.FromDateTime(DateTime.Now);
            DateOnly today = DateOnly.FromDateTime(DateTime.Now);
            DateOnly dt = DateOnly.FromDateTime(DateTime.Now.AddDays(1));


            //bool ax = Holidays.Contains(dt);
            while (Holidays.Contains(dt))
            {
                dt = dt.AddDays(1);
            }



            PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            {
                if(!GetDeliveryDateOnlyOnce)
                {
                    this.DeliveryDate = dt.ToDateTime(new TimeOnly(0, 0, 0));
                    GetDeliveryDateOnlyOnce = true;
                }
                //this.DeliveryDate = dt.ToDateTime(new TimeOnly(0, 0, 0));
                // 根据当前时间与比较时间的关系设置 MinDeliveryDate
                if (currentTime > comparisonTime)
                {
                    this.MinDeliveryDate = dt.ToDateTime(new TimeOnly(0, 0, 0));
                }
                else
                {
                    this.MinDeliveryDate = today.ToDateTime(new TimeOnly(0, 0, 0));
                }

                this.MaxDeliveryDate = dt.ToDateTime(new TimeOnly(0, 0, 0)).AddDays(30); //最大询清算交割速度改为 30天
            });

        }

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {

        }
        //private async void UpdateFilterTrades()
        //{
        //    try
        //    {
        //        if (Trades == null || Trades.Count == 0)
        //            return;

        //        DateTime today = DateTime.Today;
        //        AppLog.WriteInfo("执行UpdateFilterTrades");

        //        List<TradeHistoryRow> tempTrades;
        //        int refCount;

        //        lock (_tradesLock)
        //        {
        //            if (IsForward == false)
        //            {
        //                refCount = Trades.Count(o => o.TradeDate.Date == today && o.DealType == "REF");
        //                tempTrades = Trades.Where(tr => tr.TradeDate.Date == today && tr.Forward == this.IsForward && tr.DealType != "REF")
        //                                    .OrderByDescending(tr => tr.TradeDate)
        //                                    .ThenByDescending(tr => tr.TradeTime)
        //                                    .ToList();
        //            }
        //            else
        //            {
        //                refCount = Trades.Count(o => o.TradeDate.Date == today && o.DealType == "REF");
        //                tempTrades = Trades.Where(tr => tr.TradeDate.Date == today && tr.DealType != "REF")
        //                                    .OrderByDescending(tr => tr.TradeDate)
        //                                    .ThenByDescending(tr => tr.TradeTime)
        //                                    .ToList();
        //            }
        //        }

        //        // 使用 Task.Run 进行并行处理
        //        //Parallel.ForEach(tempTrades, trade =>
        //        //{
        //        //     PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //        //    {
        //        //        trade.SettleSpeed = DeliverySpeedConverter.ConvertToSpeed(trade.SettleSpeed, Holidays);
        //        //    });

        //        //});
        //        // 使用异步方法并行处理
        //        var tasks = tempTrades.Select(async trade =>
        //        {
        //            // 需要将此操作移到 UI 线程中
        //            await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //            {
        //                trade.SettleSpeed = DeliverySpeedConverter.ConvertToSpeed(trade.SettleSpeed, Holidays);
        //            });
        //        });

        //        await Task.WhenAll(tasks);
        //        // 在UI线程上更新FilteredTrades
        //        await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //        {
        //            try
        //            {
        //                lock (_tradesLock)
        //                {
        //                    AppLog.WriteError($"券号:{this.BondNumber} Trades改变更新FilteredTrades交易数据。第{++b}次");
        //                    FilteredTrades = new ObservableCollection<TradeHistoryRow>(tempTrades);

        //                    BidCount = FilteredTrades.Count(o => o.DealType == "TKN");
        //                    OfrCount = FilteredTrades.Count(o => o.DealType == "GVN");
        //                    TrdCount = FilteredTrades.Count(o => o.DealType == "TRD");
        //                    AllCount = FilteredTrades.Count();

        //                    int aa = refCount;
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                AppLog.WriteFatal($"在UI线程上更新FilteredTrades时发生异常: {ex.Message}");
        //                // 这里可以添加其他异常处理逻辑，比如通知用户或重新抛出异常
        //            }
        //        });
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteFatal($"在UpdateFilterTrades方法中发生异常: {ex.Message}");
        //        // 这里可以添加其他异常处理逻辑，比如通知用户或重新抛出异常
        //    }
        //}

        List<TradeHistoryRow> tempTrades;

        private async Task UpdateFilterTrades()
        {
            try
            {
                //List<TradeHistoryRow> tempTrades = new List<TradeHistoryRow>();
                int refCount = 0;

                if (Trades != null && Trades.Count > 0)
                {
                    DateTime today = DateTime.Today;

                    //AppLog.WriteInfo("执行UpdateFilterTrades");

                    List<TradeHistoryRow> tradesCopy;
                    lock (_tradesLock)
                    {
                        tradesCopy = new List<TradeHistoryRow>(Trades);
                    }

                    if (IsForward == false)
                    {
                        refCount = tradesCopy.Count(o => o.TradeDate.Date == today && o.DealType == "REF");
                        tempTrades = tradesCopy.Where(tr => tr.TradeDate.Date == today && tr.Forward == this.IsForward && tr.DealType != "REF")
                                               .OrderByDescending(tr => tr.TradeDate)
                                               .ThenByDescending(tr => tr.TradeTime)
                                               .ToList();
                    }
                    else
                    {
                        refCount = tradesCopy.Count(o => o.TradeDate.Date == today && o.DealType == "REF");
                        tempTrades = tradesCopy.Where(tr => tr.TradeDate.Date == today && tr.DealType != "REF")
                                               .OrderByDescending(tr => tr.TradeDate)
                                               .ThenByDescending(tr => tr.TradeTime)
                                               .ToList();
                    }

                    if (tempTrades == null)
                    {
                        return;
                    }
                    // 在后台线程上进行转换


                    //await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                    //{
                    //    foreach (var trade in tempTrades)
                    //    {
                    //        trade.SettleSpeed = DeliverySpeedConverter.ConvertToSpeed(trade.SettleSpeed, Holidays);
                    //    }
                    //});


                    // 在UI线程上更新FilteredTrades
                    await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                    {
                        try
                        {
                            //lock (LilyTradeLock)
                            //{
                                //AppLog.WriteError($"券号:{this.BondNumber} Trades改变更新FilteredTrades交易数据。第{++b}次");
                                FilteredTrades = new ObservableCollection<TradeHistoryRow>(tempTrades);

                                BidCount = FilteredTrades.Count(o => o.DealType == "TKN");
                                OfrCount = FilteredTrades.Count(o => o.DealType == "GVN");
                                TrdCount = FilteredTrades.Count(o => o.DealType == "TRD"||o.DealType=="Done");
                                AllCount = FilteredTrades.Count();

                                //AppLog.WriteInfo($"{MsgToken}\r\n AA{this.BondNumber}-TKN:{BidCount}条，GVN：{OfrCount}条，所有：{AllCount}条");
                            //}
                        }
                        catch (Exception ex)
                        {
                            AppLog.WriteError($"在UI线程上更新FilteredTrades时发生异常: {ex.Message}");
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"在UpdateFilterTrades方法中发生异常: {ex.Message}");
            }
        }
        //private  void UpdateFilterTrades()
        //{
        //    try
        //    {


        //        int refCount = 0;
        //        if (Trades != null && Trades.Count > 0)
        //        {
        //            DateTime today = DateTime.Today;

        //            AppLog.WriteInfo("执行UpdateFilterTrades");

        //            // 创建临时集合来避免在UI线程外部操作UI绑定的集合



        //            lock (_tradesLock)
        //            {
        //                if (IsForward == false)
        //                {
        //                    refCount = Trades.Where(o => o.TradeDate.Date == today && o.DealType == "REF").Count();
        //                    tempTrades = Trades.Where(tr => tr.TradeDate.Date == today && tr.Forward == this.IsForward && tr.DealType != "REF")
        //                                                .OrderByDescending(tr => tr.TradeDate)
        //                                                .ThenByDescending(tr => tr.TradeTime)
        //                                                .ToList();

        //                }
        //                else
        //                {
        //                    refCount = Trades.Where(o => o.TradeDate.Date == today && o.DealType == "REF").Count();
        //                    tempTrades = Trades.Where(tr => tr.TradeDate.Date == today && tr.DealType != "REF")
        //                                                .OrderByDescending(tr => tr.TradeDate)
        //                                                .ThenByDescending(tr => tr.TradeTime)
        //                                                .ToList();
        //                }
        //                // 使用并行处理来优化替换 SettleSpeed 字段的操作


        //                Parallel.ForEach(tempTrades, trade =>
        //                {
        //                    PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //                    {
        //                        trade.SettleSpeed = DeliverySpeedConverter.ConvertToSpeed(trade.SettleSpeed, Holidays);
        //                    });

        //                });
        //            }


        //            //await Task.Delay(200);

        //            // 在UI线程上更新FilteredTrades
        //            // 在UI线程上更新FilteredTrades
        //            PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //            {
        //                try
        //                {

        //                    lock (_tradesLock)
        //                    {
        //                        AppLog.WriteError($"券号:{this.BondNumber} Trades改变更新FilteredTrades交易数据。第{++b}次");
        //                        FilteredTrades = new ObservableCollection<TradeHistoryRow>(tempTrades);

        //                        BidCount = FilteredTrades.Where(o => o.DealType == "TKN").Count();
        //                        OfrCount = FilteredTrades.Where(o => o.DealType == "GVN").Count();
        //                        TrdCount = FilteredTrades.Where(o => o.DealType == "TRD").Count();
        //                        AllCount = FilteredTrades.Count();

        //                        int aa = refCount;
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    AppLog.WriteFatal($"在UI线程上更新FilteredTrades时发生异常: {ex.Message}");
        //                    // 这里可以添加其他异常处理逻辑，比如通知用户或重新抛出异常
        //                }
        //            });
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteFatal($"在UpdateFilterTrades方法中发生异常: {ex.Message}");
        //        // 这里可以添加其他异常处理逻辑，比如通知用户或重新抛出异常
        //    }
        //}

        #region WebSocket通讯相关
        public ClientWebSocketHelper websocket { get; set; }

        int c = 0;

        private object LilyTradeLock = new object();
        /// <summary>
        /// 订阅下单事件
        /// </summary>
        /// <param name="TsCode"></param>
        /// <param name="Bids"></param>
        /// <param name="BidType"></param>
        /// <exception cref="NotImplementedException"></exception>
        private async Task Websocket_SubscribeAllBidEvent(string TsCode, List<BidHistory> Bids, int BidType)
        {
            try
            {
                // 如果没有 TsInfo 或 Bids 为空，直接返回
                if (TsInfo == null || Bids == null || Bids.Count == 0)
                {
                    return;
                }

                //lock (LilyTradeLock)
                //{
                    // 根据 BidType 处理
                    if (BidType == 1)
                    {
                        TotalBids.Ofrs = Bids;

                        if (TsCode == TsInfo.tsCode)
                        {
                           await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                            {
                                if (this.IsForward == false)
                                {
                                    this.Ofrs = new ObservableCollection<BidHistory>(
                                        Bids.Where(o => o.Forward == this.IsForward).OrderBy(item =>
                                        {
                                            return ChatReceivers.Count(x => x.Brokerid == item.BrokerId) == 0 ? -1 : 1;
                                        }));
                                }
                                else
                                {
                                    this.Ofrs = new ObservableCollection<BidHistory>(
                                        Bids.OrderBy(item =>
                                        {
                                            return ChatReceivers.Count(x => x.Brokerid == item.BrokerId) == 0 ? -1 : 1;
                                        }));
                                }

                                UpdateIsBrokerOccupied(this.Ofrs);
                            });
                        }
                    }
                    else
                    {
                        TotalBids.Bids = Bids;

                        if (TsCode == TsInfo.tsCode)
                        {
                          await  PrismApplication.Current.Dispatcher.InvokeAsync(new Action(() =>
                            {
                                if (this.IsForward == false)
                                {
                                    this.Bids = new ObservableCollection<BidHistory>(
                                        Bids.Where(o => o.Forward == this.IsForward).OrderBy(item =>
                                        {
                                            return ChatReceivers.Count(x => x.Brokerid == item.BrokerId) == 0 ? 1 : -1;
                                        }));
                                }
                                else
                                {
                                    this.Bids = new ObservableCollection<BidHistory>(
                                        Bids.OrderBy(item =>
                                        {
                                            return ChatReceivers.Count(x => x.Brokerid == item.BrokerId) == 0 ? 1 : -1;
                                        }));
                                }
                                UpdateIsBrokerOccupied(this.Bids);
                            }));
                        }
                    
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("Websocket_SubscribeAllBidEvent: " + ex.StackTrace + ex.Message);
            }
        }

        private void UpdateIsBrokerOccupied(ObservableCollection<BidHistory> collection)
        {
            if (OrderListViewModel.IsQiangPing)
            {
                foreach (var item in collection)
                {
                    // 设置是否被占用的状态
                    item.IsBrokerOccupied = true;
                }
                return;
            }
            if (OccupiedBroker != null && OccupiedBroker.Any())
            {
                // 获取所有被占用的 broker Ids
                var occupiedBrokerIds = OccupiedBroker.Select(b => b.BrokerId).ToList();

                foreach (var item in collection)
                {
                    // 设置是否被占用的状态
                    item.IsBrokerOccupied = !occupiedBrokerIds.Contains(item.BrokerId);
                }
            }
            else
            {
                foreach (var item in collection)
                {
                    var brokerInfo = this.BrokerInfosByLily.FirstOrDefault(b => b.BrokerId == item.BrokerId);
                    item.IsBrokerOccupied = brokerInfo != null && brokerInfo.Occupy;
                }
            }
        }


        private static object obj = new object();
        private string ServerIP = null;
        public void StartConnection()
        {
            websocket = new ClientWebSocketHelper(_dailyData);
            //事件分下类
            websocket.SubscribeTradeEvent -= Websocket_SubscribeTradeEvent; // lily
            websocket.SubscribeAllBidEvent -= Websocket_SubscribeAllBidEvent; //lily
            websocket.ServerDisconnectedEvent -= Websocket_ServerDisconnectedEvent;//我的服务端
            websocket.ServerConnectedEvent -= Websocket_ServerConnectedEvent;//我的服务端
            websocket.LilyWebSocketDisconnectedEvent -= LilyWebSocketDisconnectedEvent;//Lily断连
            websocket.LilyWebSocketConnectedEvent -= LilyWebSocketConnectedEvent;//Lily连接


            //websocket.SubscribeLilyTradeEvent += Websocket_SubscribeLilyTradeEvent;

            websocket.TradeAmountLimitEvent -= WebSocketHelper_TradeAmountLimitEvent;//lily
            websocket.QuanYiOrderClientMessageEvent -= WebSocketHelper_QuanYiOrderClientMessageEvent;//我的服务端

            websocket.AllWebSocketMessagesReceived -= Websocket_AllWebSocketMessagesReceived;

            websocket.SubscribeTradeEvent += Websocket_SubscribeTradeEvent;
            websocket.SubscribeAllBidEvent += Websocket_SubscribeAllBidEvent;
            websocket.ServerDisconnectedEvent += Websocket_ServerDisconnectedEvent;
            websocket.ServerConnectedEvent += Websocket_ServerConnectedEvent;
            websocket.LilyWebSocketDisconnectedEvent += LilyWebSocketDisconnectedEvent;//Lily断连
            websocket.LilyWebSocketConnectedEvent += LilyWebSocketConnectedEvent;//Lily连接


            //websocket.SubscribeLilyTradeEvent += Websocket_SubscribeLilyTradeEvent;

            websocket.TradeAmountLimitEvent += WebSocketHelper_TradeAmountLimitEvent;
            websocket.QuanYiOrderClientMessageEvent += WebSocketHelper_QuanYiOrderClientMessageEvent;

            websocket.AllWebSocketMessagesReceived += Websocket_AllWebSocketMessagesReceived;
            lock (obj)
            {
                websocket.GetTradeLimit();
            }
            ServerIP = OrderListViewModel.ServerIP;
            //ServerIP = _dailyData.GetConfigs("WeChatServer")[0].Value;0831
            //string ServerIP
            //if (websocket.ClientStartConnectToServer(ServerIP, 38888))
            //{
            //    bIsConnected = true;
            //    IsLoading = false;
            //    AppLog.WriteInfo($"券号为{this.BondNumber}的连接Lily成功");
            //    //return true;
            //}
            //else
            //{
            //    bIsConnected = false;
            //    IsLoading = true;
            //    LoadingMessage = "与服务器连接断开";
            //    AppLog.WriteInfo($"券号为{this.BondNumber}的连接Lily失败！！！");
            //    //return false;
            //}

            if (websocket.ClientStartConnectToServer(ServerIP, 38888))
            {
                bIsConnected = true;
                IsLoading = false;
                //return true;
            }
            else
            {
                bIsConnected = false;
                IsLoading = true;
                LoadingMessage = "与服务器连接断开";
                AppLog.WriteError($"与38888服务器连接断开");
                // 启动定时器尝试重连
                StartReconnectLXWServerTimer();
             
                //return false;
            }
        }

        private void LilyWebSocketConnectedEvent(string guid)
        {
            AppLog.WriteInfo("与Lily服务端连接成功");
            //Growl.InfoGlobal("与Lily服务端连接成功" + GuidStr);
            IsLilyWebSocketConnected = true;
        }

        private void LilyWebSocketDisconnectedEvent()
        {
           
            try
            {
              
                IsLilyWebSocketConnected = false;
                AppLog.WriteError("下单界面与Lily服务端断连了");
                if (!string.IsNullOrEmpty(this.BondNumber))
                {


                    // 初始化定时器，每5秒执行一次
                    _restartLilyTimer = new System.Threading.Timer(CheckAndReconnect, null, TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60));
                    //websocket.SubscribeTradeData(this.BondNumber,this.GuidStr);
                    AppLog.WriteError($"断连重新订阅{this.BondNumber}");



                }


            }
            catch (Exception ex)
            {
                AppLog.WriteError("OrderViewModel——Websocket_ServerDisconnectedEvent连接我的服务端" + ex.StackTrace + ex.Message);
            }
        }

        private bool isReconnecting = false;

        private System.Timers.Timer reconnectTimer;
        private void StartReconnectLXWServerTimer()
        {
            // 如果正在尝试重连，则直接返回
            if (isReconnecting)
                return;

            // 设置正在重连标志
            isReconnecting = true;

            // 创建并配置定时器
            reconnectTimer = new System.Timers.Timer();
            reconnectTimer.Interval = 10000; // 设置重连间隔为15秒
            reconnectTimer.Elapsed -= ReconnectTimer_Elapsed;

            reconnectTimer.Elapsed += ReconnectTimer_Elapsed;
            reconnectTimer.AutoReset = true; // 设置为true，确保定时器重复执行

            // 启动定时器
            reconnectTimer?.Start();
        }
        private void ReconnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // 在定时器触发时执行重连操作
            bool isConnected = websocket.ClientStartConnectToServer(ServerIP, 38888);

            if (isConnected)
            {
                // 连接成功，停止定时器并重置标志
                reconnectTimer?.Stop();
                isReconnecting = false;
                IsLoading = false;
                bIsConnected = true;
                AppLog.WriteWarn("重新连接LXW服务器失败");
                //reconnectAttempt = 0; // 重置重连尝试次数
                // 可以在这里执行连接成功后的逻辑
            }
            else
            {
                AppLog.WriteWarn("连接LXW服务器失败");
                //Growl.WarningGlobal($"连接服务器失败,第{++reconnectAttempt}次");
                // 连接失败，可以记录日志或者显示提示信息等
            }
        }

        /// <summary>
        /// 测试，接收刘老师所有websocket消息
        /// </summary>
        /// <param name="message"></param>
        private void Websocket_AllWebSocketMessagesReceived(string message)
        {
            Growl.InfoGlobal("websocket消息" + message);
        }

        private void Websocket_QiangpingEvent(PlaceOrder_Shared.ModelsToLily.QiangPingOrder qiangPingOrder)
        {
            string msg = qiangPingOrder.Message;
            // 通过强制转换为你的窗体类型来关闭窗体
            (PrismApplication.Current.MainWindow as OrderView)?.Close();
            Growl.InfoGlobal("提示：出现强平信息！！！" + "\r\n" + msg);
        }

        private QuanYiOrderServerResponseClass GlobalQSR = new QuanYiOrderServerResponseClass();
        private void WebSocketHelper_QuanYiOrderClientMessageEvent(QuanYiOrderServerResponseClass QSR)
        {
            try
            {
                if (QSR.Guid == CurrentGuid)
                {
                    GlobalQSR = QSR;
                    bResponseReceived = true;

                    Messenger.Default.Send(QSR, MessageToken.SendToOrderListViewOrderInfo);
                }


            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "QuanyiServer" + "Socket_QuanYiClientMessageEvent" + ex.StackTrace);
                QSR.Code = 7;
                QSR.Message = ex.Message;
                //websocket.SendResponseToClient(QSR);
            }
        }
        private readonly object lockTradeAmountLimit = new object();
        private async void WebSocketHelper_TradeAmountLimitEvent()
        {
            if (TsInfo == null)
                return;
            //if (UserHelper.TradeLimit == null)
            //{
            //    UserHelper.TradeLimit = new UserTradeLimit();
            //}
            // 从接口获取最大可买可卖量
            int[] maxBidVolumes = await UserHelper.GetMaxBidVolumeAsync(TsInfo.tsCode);

            if (maxBidVolumes == null || maxBidVolumes.Length < 2)
            {
                maxBidVolumes = new int[] { 0, 0 };
            }
          
              await  PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                {
                    MaxBidVolume = RoundDownToNearestThousand((int)(maxBidVolumes[0]));
                    MaxOfrVolume = RoundDownToNearestThousand((int)(maxBidVolumes[1]));

                    //MaxBidVolume = RoundDownToNearestThousand((int)(maxBidVolumes[0] * DailyData.DefaultPVBP / TsInfo.PVBP));
                    //MaxOfrVolume = RoundDownToNearestThousand((int)(maxBidVolumes[1] * DailyData.DefaultPVBP / TsInfo.PVBP));
                    //int InitMaxVolume = (int)(UserHelper.TradeLimit.InitMaxVolume * DailyData.DefaultPVBP / TsInfo.PVBP) / 1000 * 1000;
                    TradeLimit = $"剩余买:{MaxBidVolume},剩余卖:{MaxOfrVolume}";
                    //AppLog.WriteInfo($"券码{this.TsInfo.tsCode}。最大可买---{MaxBidVolume}/最大可卖---{MaxOfrVolume}调整。");
                    MaxVolumeAccount = Math.Max(MaxBidVolume, MaxOfrVolume);
                });

            


            //if (UserHelper.TradeLimit.MaxBidVolume > 0)
            //{
            //    this.isLoading = true;
            //}
            //nVolume.Properties.MaxValue = InitMaxVolume;
        }

        /// <summary>
        /// 向下取整
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        int RoundDownToNearestThousand(int value)
        {
            if (value < 2000)
            {
                return 0;
            }
            else
            {
                int result = value / 1000 * 1000; // 向下取整到最近的千位数
                return result;
            }
        }

        private readonly object _tradesLock = new object();
        int a = 0;
        int b = 0;
        //private Guid guidTest = new Guid();
        private async Task Websocket_SubscribeTradeEvent(TradeHistoryRow trade)
        {
            // 锁定 Trades 集合以确保线程安全
            try
            {
                if(trade.TsCode!=trade.TsCode)
                {
                    AppLog.WriteError("websocket的TsCode和当前TsCode不一致.TradeId="+trade.TradeID);
                    return;
                }
                await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                {
                  
                        //trade.SettleSpeed = DeliverySpeedConverter.ConvertToSpeed(trade.SettleSpeed, Holidays);
                        if (this.Trades != null)
                        {
                            if(trade.DealType.ToLower()=="ref")
                            {
                                // 查找是否存在 TradeID 匹配的交易
                                var tradeToRemove = Trades.FirstOrDefault(o => o.TradeID == trade.TradeID);

                                // 如果找到了，则移除该项
                                if (tradeToRemove != null)
                                {
                                    Trades.Remove(tradeToRemove);
                                    AppLog.WriteFatal("该单是REF，需要撤单,TradeId是："+trade.TradeID+"券码是："+this.BondNumber);
                                    return;
                                }
                            }
                            Trades.Add(trade);
                        }
                    
                });
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"券号:{this.BondNumber}--收到交易数据异常。{ex.Message}");
            }
        }

        public void DisposeAllTimers()
        {
            AppLog.WriteInfo("销毁所有定时器");
            this._timer.Stop();
            this._timer = null;
            this._restartLilyTimer?.Dispose();
        }
        private void Websocket_SubscribeLilyTradeEvent(LilyTradeModel Trade)
        {

        }
        private bool IsLilyWebSocketConnected = false;
        private System.Threading.Timer _restartLilyTimer;
        private void Websocket_ServerConnectedEvent()
        {
            AppLog.WriteInfo("与我的服务端连接成功");
            //Growl.InfoGlobal("与LXW下单服务端连接成功" + GuidStr);
            bIsConnected = true;
            IsLoading = false;
        }
        public void StartConnectionMonitor()
        {
            // 初始化定时器，每5秒执行一次
            Growl.InfoGlobal("开启lily重连定时器" + GuidStr);

            _restartLilyTimer = new System.Threading.Timer(CheckAndReconnect, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
        }

        private void CheckAndReconnect(object? state)
        {
            if (!IsLilyWebSocketConnected)
            {
                try
                {
                    // 尝试重新连接
                    if(websocket==null)
                    {
                        websocket = new ClientWebSocketHelper(_dailyData);
                    }
                    websocket.SubscribeTradeEvent -= Websocket_SubscribeTradeEvent;
                    websocket.SubscribeAllBidEvent -= Websocket_SubscribeAllBidEvent;
             
                    websocket.LilyWebSocketDisconnectedEvent -= LilyWebSocketDisconnectedEvent;
                    websocket.LilyWebSocketConnectedEvent -= LilyWebSocketConnectedEvent;


                    //websocket.SubscribeLilyTradeEvent += Websocket_SubscribeLilyTradeEvent;

                    websocket.TradeAmountLimitEvent -= WebSocketHelper_TradeAmountLimitEvent;
                    websocket.QuanYiOrderClientMessageEvent -= WebSocketHelper_QuanYiOrderClientMessageEvent;

                    websocket.AllWebSocketMessagesReceived -= Websocket_AllWebSocketMessagesReceived;

                    websocket.SubscribeTradeEvent += Websocket_SubscribeTradeEvent;
                    websocket.SubscribeAllBidEvent += Websocket_SubscribeAllBidEvent;
            

                    websocket.LilyWebSocketDisconnectedEvent += LilyWebSocketDisconnectedEvent;
                    websocket.LilyWebSocketConnectedEvent += LilyWebSocketConnectedEvent;

                    //websocket.SubscribeLilyTradeEvent += Websocket_SubscribeLilyTradeEvent;

                    websocket.TradeAmountLimitEvent += WebSocketHelper_TradeAmountLimitEvent;
                    websocket.QuanYiOrderClientMessageEvent += WebSocketHelper_QuanYiOrderClientMessageEvent;

                    websocket.AllWebSocketMessagesReceived += Websocket_AllWebSocketMessagesReceived;
                    lock (obj)
                    {
                        websocket.GetTradeLimit();
                    }
                    websocket.SubscribeTradeData(this.BondNumber, this.GuidStr);
                    Growl.InfoGlobal("正在尝试重新连接并订阅..." + GuidStr);
                    AppLog.WriteInfo("正在尝试重新连接Lily并订阅...");
                }
                catch (Exception ex)
                {
                    AppLog.WriteError("CheckAndReconnect——" + ex.StackTrace + ex.Message);
                }
            }
            else
            {
                _restartLilyTimer?.Dispose();
                _restartLilyTimer = null;
            }
        }
        public void StopConnectionMonitor()
        {
            if (_restartLilyTimer != null)
            {
                _restartLilyTimer.Dispose();
                _restartLilyTimer = null;
            }
        }
        public string GuidStr = string.Empty;
        private void Websocket_ServerDisconnectedEvent(string guid)
        {
            try
            {
                bIsConnected = false;
                AppLog.WriteError("下单界面与LXW的服务端断连了");
                if (!string.IsNullOrEmpty(this.BondNumber))
                {

                    StartReconnectLXWServerTimer();
                        //// 初始化定时器，每5秒执行一次
                        //_restartLilyTimer = new System.Threading.Timer(CheckAndReconnect, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); 
                        ////websocket.SubscribeTradeData(this.BondNumber,this.GuidStr);
                        //AppLog.WriteError($"断连重新订阅{this.BondNumber}");

                }


            }
            catch(Exception ex)
            {
                AppLog.WriteError("OrderViewModel——Websocket_ServerDisconnectedEvent连接我的服务端" + ex.StackTrace + ex.Message);
            }
            //ServerClosedDele serverClosedDele = new ServerClosedDele(ServerClosed);
            //serverClosedDele();
        }
        private delegate void ServerClosedDele();

        /// <summary>
        /// 重连服务器
        /// </summary>
        private void ServerClosed()
        {
            IsLoading = true;
            LoadingMessage = "与服务器连接断开";
            Status = "与服务器连接断开";
            bIsConnected = false;
            Task.Factory.StartNew(() =>
            {
                while (!bIsConnected)
                {
                    Task.Delay(5000).Wait();
                    StartConnection();
                    //if (StartConnection())
                    //{
                    //    isLoading = false;
                    //}
                }
            });
        }

        protected void OnThemeIndexChanged()
        {
            //switch (ThemeIndex)
            //{
            //    case 0: ApplicationThemeHelper.ApplicationThemeName = Theme.VS2019DarkName; break;
            //    case 1: ApplicationThemeHelper.ApplicationThemeName = Theme.Office2019ColorfulName; break;
            //}
        }
        #endregion
    }
}
